I'm trying to create DSN_Less linked tables of all user tables in a specified database in sql server To an Access FE.
While the following code works and I have no problem with it, I thought before taking any stupid step and going further, I better ask for someone checking it. (specially connection strings)
Any correction (if necessary) is much appreciated.
While the following code works and I have no problem with it, I thought before taking any stupid step and going further, I better ask for someone checking it. (specially connection strings)
Any correction (if necessary) is much appreciated.
Code:
Sub Add_DSNLessTables()
Dim stConnect As String
Dim sql As String
Dim db As DAO.Database
Dim tbl As String
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
stConnect = "DRIVER=ODBC Driver 18 for SQL Server;SERVER=Server;DATABASE=Designers;Trusted_Connection=Yes;Encrypt=no;"
Set db = CurrentDb
With con
.ConnectionString = stConnect
.ConnectionTimeout = 10
.Open
End With
If con.State = 0 Then Exit Sub
sql = "select * from sys.tables where type = 'U'"
rs.CursorLocation = adUseClient
rs.Open sql, con, adOpenStatic
stConnect = "ODBC;DRIVER=ODBC Driver 18 for SQL Server;SERVER=Server;DATABASE=Designers;Trusted_Connection=Yes;Encrypt=no;"
Do
tbl = rs.Fields("name")
If DCount("[Name]", "MSysObjects", "[Name] = '" & tbl & "'") = 1 Then
' table exists. Refresh the link
db.TableDefs(tbl).Connect = stConnect
Else
' table doesn't exits. Add it
AddLinkedTable tbl, tbl, stConnect
End If
rs.MoveNext
Loop Until rs.EOF
End Sub
Public Function AddLinkedTable(strNameInSQLServer As String, _
strNameInAccess, _
stConnect As String)
DoCmd.TransferDatabase acLink, "ODBC Database", stConnect, acTable, strNameInSQLServer, strNameInAccess
End Function
Last edited: