I have an MS Access program which contains a number of SQL tables which are linked to Azure SQL server. Ideally I would like to create a login procedure via a popup form, in which I would ask the user for credentials where I would then update the linked tables and pass through queries with the required data. However I can't get this to work. The code runs fine without error messages, however when I - after executing the procedure - open a form that contains a linked table, I still get the request to login. The idea is to have the login procedure run at the startup screen, with the user not being asked to enter credentials anywhere after successful login.
This is the code I am using for this:
Public Function ConnectToAzureSQL(sServer As String, sDatabase As String, sUserName As String, sPassWord As String)
On Error GoTo Proc_err
Dim con As Object
Dim var As Variant
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Set db = CurrentDb
Set con = CreateObject("ADODB.Connection")
strConnect = "DRIVER={ODBC Driver 17 for SQL Server}" & _
";Server=sServer" & _
";Database=sDatabase" & _
";UID=sUserName" & _
"PWD=sPassWord".
con.Open strConnect
For Each tdf In db.TableDefs
Debug.Print tdf.Name
If Len(tdf.Connect) Then
tdf.Connect = strConnect
tdf.RefreshLink
End If
Next
con.Close
Proc_exit:
MsgBox ("done")
Exit Function
Proc_err:
Debug.Print Err.Description & " : " & Str(Err.Number)
Resume Proc_exit
End Function
What I forgot to mention is that this method uses the SQL server login method. Fortunately, I found the answer myself. Should anyone need it, here is the procedure. The disadvantage of this method is that the login data is captured in the connection string. On second thought, I opted for the Azure Active Directory login method with MFA, where no password is stored in your application.
Public Function ConnectToAzureSQL(sServer, sDb, sUID, sPWD As String, bConn As Boolean)
On Error GoTo Proc_err
Dim con As Object
Dim var As Variant
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Set db = CurrentDb
Set con = CreateObject("ADODB.Connection")
sConnect = "DRIVER={ODBC Driver 17 for SQL Server}" & _
";Server=" & sServer _
& ";Database=" & sDb _
& ";UID=" & sUID _
& ";PWD=" & sPWD
con.Open strConnect
bConn = True
DoCmd.OpenForm "Frm_Bericht"
For Each tdf In db.TableDefs
If Len(tdf.Connect) Then
tdf.Connect = strConnect & ";UID=" & sUID & ";PWD=" & sPWD
Forms!Frm_Bericht.Caption = "Update verbinding naar tabel: " & tdf.Name
tdf.RefreshLink
End If
Next
con.Close
DoCmd.Close acForm, "Frm_Bericht"
Proc_exit:
Exit Function
Proc_err:
Debug.Print Err.Description & " : " & Str(Err.Number)
Resume Proc_exit
End Function