Я пытался создать связанную таблицу в Access, используя соединение без DSN с VBA. Я нашел в Интернете действительно полезную ссылку это. Вот код по ссылке:
'//Name : AttachDSNLessTable
'//Purpose : Create a linked table to SQL Server without using a DSN
'//Parameters
'// stLocalTableName: Name of the table that you are creating in the current database
'// stRemoteTableName: Name of the table that you are linking to on the SQL Server database
'// stServer: Name of the SQL Server that you are linking to
'// stDatabase: Name of the SQL Server database that you are linking to
'// stUsername: Name of the SQL Server user who can connect to SQL Server, leave blank to use a Trusted Connection
'// stPassword: SQL Server user password
Function AttachDSNLessTable(stLocalTableName As String, stRemoteTableName As String, stServer As String, stDatabase As String, Optional stUsername As String, Optional stPassword As String)
On Error GoTo AttachDSNLessTable_Err
Dim td As TableDef
Dim stConnect As String
For Each td In CurrentDb.TableDefs
If td.Name = stLocalTableName Then
CurrentDb.TableDefs.Delete stLocalTableName
End If
Next
If Len(stUsername) = 0 Then
'//Use trusted authentication if stUsername is not supplied.
stConnect = "ODBC;DRIVER=SQL Server;SERVER = " & stServer & ";DATABASE = " & stDatabase & ";Trusted_Connection=Yes"
Else
'//WARNING: This will save the username and the password with the linked table information.
stConnect = "ODBC;DRIVER=SQL Server;SERVER = " & stServer & ";DATABASE = " & stDatabase & ";UID = " & stUsername & ";PWD = " & stPassword
End If
Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, stConnect)
CurrentDb.TableDefs.Append td
AttachDSNLessTable = True
Exit Function
AttachDSNLessTable_Err:
AttachDSNLessTable = False
MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description
End Function
Как видите, каждый tabledef добавляется в конце с помощью
CurrentDb.TableDefs.Append td
Код прошел без ошибок. Но в моем Access таблицы не появились. Только когда я сжал и восстановил базу данных, таблицы появились. Понятия не имею, почему это происходит.
После добавления объекта в коллекцию необходимо обновить коллекцию: CurrentDb.TableDefs.Refresh
.
И чтобы увидеть изменения в окне базы данных: Application.RefreshDatabaseWindow
The RefreshDatabaseWindow method updates the Database window (Database window: In Access 2003 and earlier, the window that appears when a database or project is opened. It displays shortcuts for creating new database objects and opening existing objects. In later versions, it is replaced by the Navigation Pane.) after a database object (database objects: An Access database contains objects such as tables, queries, forms, reports, pages, macros, and modules. An Access project contains objects such as forms, reports, pages, macros, and modules.) has been created, deleted, or renamed.
Имеет смысл. Я только что добавил Application.RefreshDatabaseWindow, и это сработало. Не нужно было использовать CurrentDb.TableDefs.Refresh.
@namko CurrentDb.TableDefs.Refresh
обновляет только одну коллекцию TableDefs
, а не окно базы данных. Пока RefreshDatabaseWindow
обновляет семь коллекций, и перерисовывает окно базы данных.
Безусловно верно. Справочный код Microsoft не включает это, потому что, если вы хотите присоединить несколько таблиц, вы обычно хотите запустить эти два оператора только один раз (после добавления всех таблиц).