Question

Hello everyone I have spent a few days looking at ways to connect to SQL server using vba and found an interesting post by microsoft on how to setup a DSN-less connection they have provided the code this is what it looks like.

'//Name :AttachDSNLessTable
'//Purpose:Create a linked table to SQL Server without using a DSN 
'//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


Private Sub Form_Open(Cancel As Integer)
If AttachDSNLessTable("authors", "authors", "(local)", "pubs", "", "") Then
    '// All is okay.
Else
    '// Not okay.
End If
End Sub

My problem here is that this code works but it does not work properly for me because if I were to hand this form to someone else they will not be able to open it because the event is set in Form_open and you cant open the form unless you already have the data table available. Is there a better event feature I can use to get this to create the DSN-less connection before I open the form?

This is the error I receive if I try to open the form without a set DSN "The record source specified on this form or report does not exist."

Here is the link to the source http://support.microsoft.com/kb/892490 I used method 1.

Was it helpful?

Solution

If this code works for you but you need a better place to execute it/a place that will execute that is not tied to that form's definition you can run it in the AutoExec macro.

The AutoExec macro is a macro named AutoExec which runs when you start your Access app. You can use the RunCode macro function to call your VBA function (it does have to be a function and not a sub).

This way you can (re)link your table before the form is even opened.

OTHER TIPS

Open a blank form, with a fixed data record as source. Run your Code, then change the source form to your real form (VBA Code in OPEN FORM action) according to what you want to do. This is SMOKE and MIRROW Code. You will have one hell of a time debugging it.

I just want to share in case someone would need original source: https://www.wiseowl.co.uk/blog/s285/linkviewsvba.htm

' we will need to create this table using DAO

Dim tdf As DAO.TableDef

' Some variable to make the code more generic

Dim strConnectionString As String

Dim strNameInAccess As String

Dim strNameInSQLServer As String

Dim strKey As String

' set the connection string

strConnectionString = "ODBC;DRIVER=SQL Server; " & " SERVER=xx.xx.xxx.xx,xxxx;DATABASE=MYDATABASENAME;Trusted_Connection=No;UID=MYID;PWD=@MyPass!"

' specify the tables you want to link. The table can be

' known by a different name in Access than the name in SQL server

strNameInAccess = "LINKTABONEATTMT"

strNameInSQLServer = "TABONEATTMT"

' specify the key field

strKey = "ID"

' Delete the table from the local database if it exists

On Error Resume Next

DoCmd.RunSQL "drop table " & strNameInAccess

On Error GoTo 0

' Create a table using DAO give it a name in Access.

' Connect it to the SQL Server database.

' Say which table it links to in SQL Server.

Set tdf = CurrentDb.CreateTableDef(strNameInAccess)

tdf.Connect = strConnectionString

tdf.SourceTableName = strNameInSQLServer

' Add this table Definition to the collection

' of Access tables

CurrentDb.TableDefs.Append tdf

' Now create a unique key for this table by

' running this SQL

On Error Resume Next

DoCmd.RunSQL "CREATE UNIQUE INDEX UniqueIndex ON " & strNameInAccess & " (" & strKey & ")"

On Error GoTo 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top