是的,可以使用 VBA 进行操作,但是您执行此操作的方式实际上取决于您链接表格的方式。
这是我用于 SQL 服务器表的 2 个连接字符串示例
直接连接:
Driver=SQL Server Native Client 10.0;Server=server_name;Address=server_address,1433;Network=network_name;Database=database_name;Trusted_Connection=Yes
DSN 连接(在 ODBC 控制面板中有一个条目)
ODBC;Provider=SQLNCLI10;Server=server_name;DSN=name_of_DSN_entry_in_ODBC_control_panel;Database=database_name;Trusted_Connection=Yes
所以首先要做的是确定您的表是如何链接的。
您可以使用此代码(注意 cmets):
Public Sub Check_ODBC_tables()
Dim tdef As TableDef
' First loop on all tables to determine the connection strings
For Each tdef In CurrentDb.TableDefs
' only print the constring if the database name is your old database (adapt accordingly)
If InStr(tdef.Connect, "Database=old_database_name") Then
Debug.Print tdef.Connect
End If
Next
End Sub
运行此代码 (F5) 并检查即时窗口中的输出。您会发现表格是如何链接的以及连接字符串是什么。
您应该根据它准备一个连接字符串,并在其中调整数据库名称以使用您的新数据库。
准备就绪后,您可以调整并运行以下代码,该代码将删除旧表并使用新数据库名称重新创建它们(可能需要进行一些调整),因此请在调试模式下考虑!
Public Sub Change_ODBC_tables()
Dim tDef As TableDef
Dim tDefNew As TableDef
Dim strTable As String
Dim strCOnString As String
' examples of constrings - ADAPT!!!!
strCOnString = "Driver=SQL Server Native Client 10.0;Server=server_name;Address=server_address,1433;Network=network_name;Database=database_name;Trusted_Connection=Yes"
strCOnString = "ODBC;Provider=SQLNCLI10;Server=server_name;DSN=name_of_DSN_entry_in_ODBC_control_panel;Database=database_name;Trusted_Connection=Yes"
For Each tDef In CurrentDb.TableDefs
If InStr(tDef.Connect, "Database=old_database_name") Then
' We find a match, store the table name
strTable = tDef.Name
' delete the linked table
DoCmd.DeleteObject acTable, strTable
' recreate the linked table with new DB name
Set tDef2 = CurrentDB.CreateTableDef(strTable)
tDef2.Connect = strCOnString
tDef2.SourceTableName = strTable
tDef2.Name = strTable
CurrentDb.TableDefs.Append tDef2
End If
Next
End Sub
如果您不完全理解我发布的第二段代码,我建议您在运行之前备份您的 mdb,因为它会删除可能导致严重问题的对象。