Access database with linked tables to sql, How do I setup a ADO connection

I have a access database, with several linked tables.  By Sql Server is GCERP, my Database is called GC_Emp_data, is there away on page load that I can setup an automatic connection to there server in VB?..  with an ADO connection?  I have never done anything like this before.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
You can create an ADO connection like this:

Dim con As New ADODB.Connection
con.ConnectionString = "Provider=SQLNCLI11;Server=GCERP;Database=GC_Emp_data;Trusted_Connection=Yes"

You could then use the "con" object to open a recordset, for example

If you must use a UserID and Password, you'd use syntax like this:
con.ConnectionString = "Provider=SQLNCLI11;Server=GCERP;Database=GC_Emp_data;Uid=UserName;Pwd=Password"

Note the Provider might be different, depending on the version of SQL Server. See this website for many examples of connection string syntax:
sharris_glascolAuthor Commented:
So do I put just in place of all the other code I had?  How do I point to a table?
sharris_glascolAuthor Commented:
This was the code I was using but gave me error at the .open

Private Sub Form_Open(Cancel As Integer)
   Dim cn As ADODB.Connection
   Dim rs As ADODB.Recordset
   'Create a new ADO Connection object
   Set cn = New ADODB.Connection

   'Use the Access 10 and SQL Server OLEDB providers to
   'open the Connection
   'You will need to replace MySQLServer with the name
   'of a valid SQL Server
   With cn
      .Provider = "Microsoft.Access.OLEDB.10.0"
      .Properties("Data Provider").Value = "SQLOLEDB"
      .Properties("Data Source").Value = "GCERP"
      .Properties("User ID").Value = "sa"
      .Properties("Password").Value = "Gcdown1"
      .Properties("Initial Catalog").Value = "Gc_EMP_Data"
   End With

   'Create an instance of the ADO Recordset class, and
   'set its properties
   Set rs = New ADODB.Recordset
   With rs
      Set .ActiveConnection = cn
      .Source = "select * from Posistions"
      .LockType = adLockOptimistic
      .CursorType = adOpenKeyset
   End With
   'Set the form's Recordset property to the ADO recordset
   Set Me.Recordset = rs
   Set rs = Nothing
   Set cn = Nothing
End Sub
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
gave me error at the .open
Please always provide information about the error. Posting something like that is akin to telling your auto mechanic "it won't work" and walking away :)

If your goal is to just bind a form to the table, then the simplest way is to "link" that SQL Server table to your Access program, and then create the form as you would any other Access form. Creating a Recordset and setting the Form's Recordset property to that object can be done, but in general there's not much reason to do so.

That said: In order to link a Form's Recordset to a Recordset object, the Recordset object must use a ClientSide cursor.
sharris_glascolAuthor Commented:
Yes sorry about the vague answer..  What I am trying to do is setup this database that I am going to deploy out to the office.  I have my tables in Sql.  Right now my machine has them linked via a ODBC connection but I don't want to have to go around to each machine and setup those connections.  So do I still leave the tables linked and the On Load it will connect to the Sql server with the connection String?
Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
Did you create a DSN to do this? If so, you'd have to deploy that DSN to each user (or create a new DSN for each user), and the users would be able to use your application as-is.

I find it easier to use DSN-less tables, and setup the connection string for my linked tables on startup. Takes a little more work on your part, but overall it's fairly straight forward.

Armen Stein has a neat relink utility here: (the JStreet Relinker). That's pretty much drop in code for your needs.
sharris_glascolAuthor Commented:
Ok I am overly confused..  I have a database that I have created Linked tables on my pc that I created an ODBC connection to GCERP. Everything works great from my pc.  To get the database to work for other users, do I leave the linked tables in the database and just add the adodb connection to on page load?  Sorry very confused ...
Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
No - you would leave things as they are now, and you would "relink" the tables when needed. In many cases, you'd relink each time the application starts, so something like the JStreet relinker (above link) would be what you need.

Here's another resource for DSN-less connections: and Those should shed a bit more light on what you're trying to do.

If you don't need that, then you could always teach users how to use the Linked Table Manager (assuming they have full versions of Access, of course).

Or, you could base your connections on a DSN, and create that DSN on each user machine where your application needs to run. That would be a bit of a task, however, if you have more than a handful of machines.

Changing to ADO and Recordset-based forms would be a huge task at this point. I'd not consider that option at all ...
sharris_glascolAuthor Commented:
Thanks for the help.  so on the Macro do I have to setup one for each table. and do a call to that macro on the on load?
sharris_glascolAuthor Commented:
ok i have created a macro with this code:

Option Compare Database

'//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(dbo_Positions As String, Positions As String, GCERP As String, GC_EMP_DATA As String, Optional sa As String, Optional Gcdown1 As String)
    On Error GoTo AttachDSNLessTable_Err
    Dim td As TableDef
    Dim stConnect As String
    For Each td In CurrentDb.TableDefs
        If td.Name = dbo_Positions Then
            CurrentDb.TableDefs.Delete dbo_Positions
        End If
    If Len(sa) = 0 Then
        '//Use trusted authentication if stUsername is not supplied.
        stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & GCERP & ";DATABASE=" & GC_EMP_DATA & ";Trusted_Connection=Yes"
        '//WARNING: This will save the username and the password with the linked table information.
        stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & sa & ";DATABASE=" & GC_EMP_DATA & ";UID=" & sa & ";PWD=" & Gcdown1
    End If
    Set td = CurrentDb.CreateTableDef(dbo_Positions, dbAttachSavePWD, Positions, stConnect)
    CurrentDb.TableDefs.Append td
    AttachDSNLessTable = True
    Exit Function

    AttachDSNLessTable = False
    MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description

End Function

Then in the form_position onOpen I have put this
    If AttachDSNLessTable("authors", "authors", "(local)", "pubs", "", "") Then
        '// All is okay.
        '// Not okay.
    End If
End Sub

I am getting a Compile Error:  Expected variable or procedure, note module. and it Highlights the name AttachDSNLessTable on the form code.  Any ideas?
Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
ok i have created a macro with this code:
Do you mean you've created a VBA routine with that code? That's what you should do:

1. Create a new Standard Module. Name that Module something like "modRelink"
2. Copy and paste the code you found above into that module. Do NOT change anything - just copy it directly. The starting line of that function should read:

Function AttachDSNLessTable(stLocalTableName As String, stRemoteTableName As String, stServer As String, stDatabase As String, Optional stUsername As String, Optional stPassword As String)

Open in new window

Now, in the Open or Load event of your startup form, you'll have to call the AttachDSNLessTable. You'd have to do this for each table that needs to be reconnected. If you just have a few, you can call them directly:

AttachDSNLessTable("YourLocalTable", "TheSQLServerTableName", "GCERP", "GC_EMP_DATA", "", "")
AttachDSNLessTable("YourSecondLocalTable", "TheSecondSQLServerTableName", "GCERP", "GC_EMP_DATA", "", "")

and so on. If you have a lot of tables, you could create a new, local table in the Access database and store the Local and Remote table names, and then open a Recordset and loop through that. In that loop, you'd call the above code, which would relink your tables. The first link I provided shows how to do that.

Note also that the above calls assume you're using a TrustedConnection to the SQL Server. If you must enter a username and pass to log onto the SQL Server, you'll have to include those in the last and next-to-last arguments of the AttachDSNLessTable.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sharris_glascolAuthor Commented:
OK so I create a Macro and Copy and paste the code from the site you sent me and I did't change anything. I saved the macro to modRelink. I started this with the string you attached.

Then in my form i goto the OnOpen and attach the AttachDSNLessTable("dbo_Positions", "Positions", "GCERP", "GC_EMP_DATA", "username", "Password")  
End Sub

But it I am getting a Compile Error:  Ambiguous name detected: AttachDSNLessTable..  any ideas?
sharris_glascolAuthor Commented:
On the Main Code I pasted do I not go in and change the StLocalTableName, stRemoteTableName, .....??
sharris_glascolAuthor Commented:
Thanks for all the help yesterday.  I got it working, Can we do the same thing with a view in sql?
sharris_glascolAuthor Commented:
Was Very Helpful.
Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
Can we do the same thing with a view in sql
Not sure what you mean by that. Can you explain further?
sharris_glascolAuthor Commented:
In sql I have a view.  Can we use this same code to link to a view? or does this only work with Tables.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.