How to preserve linked tables in Access when copying to different machines - ms-access

We have a Access DB with 1000+ linked tables and about 200 local tables.
We need this Access DB to reside on the desktops of about 40 users.
The problem is, each time I copy the Access file to a new PC, even though the ODBC connection name is the same for the linked tables, it always asks me to relink all 1000+ tables and I have to click okay 1000+ times.
Is there a way to save the file in such a way that it preserves the linked relationships and the ODBC name so I can easily copy it from machine to machine?

Use a DSN-less connection and a function to relink (only needed to switch database) all the tables and pass-through queries:
Public Function AttachSqlServer( _
ByVal Hostname As String, _
ByVal Database As String, _
ByVal Username As String, _
ByVal Password As String) _
As Boolean
' Attach all tables linked via ODBC to SQL Server or Azure SQL.
' 2016-04-24. Cactus Data ApS, CPH.
Const cstrDbType As String = "ODBC"
Const cstrAcPrefix As String = "dbo_"
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim qdf As DAO.QueryDef
Dim strConnect As String
Dim strName As String
On Error GoTo Err_AttachSqlServer
Set dbs = CurrentDb
strConnect = ConnectionString(Hostname, Database, Username, Password)
For Each tdf In dbs.TableDefs
strName = tdf.Name
If Asc(strName) <> Asc("~") Then
If InStr(tdf.Connect, cstrDbType) = 1 Then
If Left(strName, Len(cstrAcPrefix)) = cstrAcPrefix Then
tdf.Name = Mid(strName, Len(cstrAcPrefix) + 1)
End If
tdf.Connect = strConnect
tdf.RefreshLink
Debug.Print Timer, tdf.Name, tdf.SourceTableName, tdf.Connect
DoEvents
End If
End If
Next
For Each qdf In dbs.QueryDefs
If qdf.Connect <> "" Then
Debug.Print Timer, qdf.Name, qdf.Type, qdf.Connect
qdf.Connect = strConnect
End If
Next
Debug.Print "Done!"
AttachSqlServer = True
Exit_AttachSqlServer:
Set tdf = Nothing
Set dbs = Nothing
Exit Function
Err_AttachSqlServer:
Call ErrorMox
Resume Exit_AttachSqlServer
End Function
Public Function ConnectionString( _
ByVal Hostname As String, _
ByVal Database As String, _
ByVal Username As String, _
ByVal Password As String, _
Optional ByVal AdoStyle As Boolean) _
As String
' Create ODBC or ADO connection string from its variable elements.
' 2021-06-15. Cactus Data ApS, CPH.
Const AzureDomain As String = ".windows.net"
Const OdbcPrefix As String = "ODBC;"
Const OdbcConnect As String = _
"DRIVER=SQL Server Native Client 11.0;" & _
"Description=Cactus TimeSag og Finans;" & _
"APP=Microsoft® Access;" & _
"SERVER={0};" & _
"DATABASE={1};" & _
"UID={2};" & _
"PWD={3};" & _
"Trusted_Connection={4};"
Dim FullConnect As String
If Right(Hostname, Len(AzureDomain)) = AzureDomain Then
' Azure SQL connection.
' Append servername to username.
Username = Username & "#" & Split(Hostname)(0)
End If
If Not AdoStyle Then
FullConnect = OdbcPrefix
End If
FullConnect = FullConnect & OdbcConnect
FullConnect = Replace(FullConnect, "{0}", Hostname)
FullConnect = Replace(FullConnect, "{1}", Database)
FullConnect = Replace(FullConnect, "{2}", Username)
FullConnect = Replace(FullConnect, "{3}", Password)
FullConnect = Replace(FullConnect, "{4}", IIf(Username & Password = "", "Yes", "No"))
ConnectionString = FullConnect
End Function
Also, study my article: Deploy and update a Microsoft Access application with one click

Related

Create a linked table in Access from Teradata without DSN?

Connection to Teradata
'Requires reference to ADO and ADOX
Public adoCn As ADODB.Connection
Public adoCat As New ADOX.Catalog
Public adoTbl As New ADOX.Table
Function TD_Make_Linked_Table()
Dim varServer As String
Dim varDatabase As String
Dim varUser As String
Dim varPassword As String
varServer = "Test"
varDatabase = "Test_Test"
varUser = "Test_User"
varPassword = "Test_Password"
Set adoCn = New ADODB.Connection
'I have tried multiple connection strings
adoCn.ConnectionString = "PROVIDER=MSDASQL;DRIVER={Teradata};" & _
"DBCName=" & varServer & ";" & _
"DefaultDatabase=" & varDatabase & ";" & _
"UID=" & varUser & ";" & _
"PWD=" & varPassword & ";"
adoCn.Open
Set adoCat = New ADOX.Catalog
Set adoCat.ActiveConnection = adoCn
Set adoTbl = New ADOX.Table
adoTbl.ParentCatalog = adoCat
adoTbl.Name = "Test"
'I have tried multiple property combinations
'Causes error 3265 Item not found
'adoTbl.Properties("?") = adoCn
'adoTbl.Properties("Jet OLEDB:Link Datasource") = "Test"
'adoTbl.Properties("Jet OLEDB:Link Provider String") =
'adoTbl.Properties("Jet OLEDB:Remote Table Name") = "LinkDatabaseTable"
'adoTbl.Properties("Jet OLEDB:Create Link") = True
'Causes 3251 provider is not capable of performing operation
'adoCat.Tables.Append adoTbl
adoCn.Close
Set adoTbl = Nothing
Set adoCat = Nothing
Set adoCn = Nothing
End Function
I have validated the connection is working. I can query data by opening the connection and executing SQL.
I am unable to create a linked table programmatically in Access using visual basic for applications with the created connection.
Has anyone been able to successfully create a linked dsn-less table from Access to Teradata?
If you have a working ODBC connection string then you should be able to use DoCmd.TransferDatabase to create a linked table. I don't have a Teradata server handy, but this works for me with SQL Server:
Dim connStr As String
connStr = _
"DRIVER=ODBC Driver 11 for SQL Server;" & _
"SERVER=(local)\SQLEXPRESS;" & _
"DATABASE=myDb;" & _
"Trusted_Connection=yes"
DoCmd.TransferDatabase _
TransferType:=acLink, _
DatabaseType:="ODBC Database", _
DatabaseName:="ODBC;" & connStr, _
ObjectType:=acTable, _
Source:="dbo.projects", _
Destination:="dbo_projects"
I eventually found a connection string that works! :)
Function adoTera()
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Set oConn = New ADODB.Connection
Set rs = New ADODB.Recordset
oConn.ConnectionString = "PROVIDER=MSDASQL;" & _
"DRIVER={Teradata};" & _
"DBCName=yourDBCName;" & _
"DefaultDatabase=yourDBName;" & _
"UID=yourUserName;" & _
"PWD=yourPassword;"
oConn.Open
rs.Open "SELECT * FROM yourTable", oConn
ThisWorkbook.Worksheets("Sheet1").Range("A:A").CopyFromRecordset rs
rs.Close
oConn.Close
Set rs = Nothing
Set con = Nothing
End Function

Access VBA - To get data from Excel file stored in Sharepoint

I have the below code working for me provided the "Model_data.xlsm" file is stored in my hard drive. Is it possible if Access can get the data from "model_data.xlsm" stored in Sharepoint?
Private Sub Update_manu_data_Click()
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "Model_data.xlsm"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Manufacturing_data", _
strXls, True, "Combined!"
End Sub
Finally I did find a workaround for this issue.
I Created a private function in access to download the Excel file from SP and then used the Transferspread sheet function to retrieve the data into access table.
Below is the code i used to download the Excel file in SP using access Vba
Private Sub Command2_Click()
Dim Ex As Object
Dim Acc As Object
Dim strXls As String
Set Ex = CreateObject("Excel.Application")
Set Acc = Ex.Workbooks.Open("https://Sharepoint File link")
Ex.Visible = False
Acc.SaveAs "C:\Users\.......\test.xlsx"
Acc.Close
Ex.Quit
strXls = CurrentProject.Path & Chr(92) & "C:\Users\.......\test.xlsx"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Tablename", _
strXls, True, "Sheet(1)!"
End Sub
Sub ConnectToExcel()
Dim strSharePointPath As String
Dim strExcelPath As String
Dim strConnectionString As String
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
' Set the SharePoint path and Excel file name
strSharePointPath = "http://yoursharepointurl.com/YourSharePointFolder/"
strExcelPath = "YourExcelFile.xlsx"
' Build the connection string
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"WSS;IMEX=0;RetrieveIds=Yes;" & _
"DATABASE=" & strSharePointPath & ";" & _
"LIST=" & strExcelPath & ";"
' Open the connection
Set cnn = New ADODB.Connection
cnn.Open strConnectionString
' Open a recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [Sheet1$]", cnn
' Loop through the recordset and display the data
Do While Not rs.EOF
Debug.Print rs.Fields(0).Value
rs.MoveNext
Loop
' Clean up
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub

Using form combo box to change server name of connection string

I am setting up an access form to enter the parameters for a query, as well as select the needed database server to connect to. This will need to be run to gather data from multiple buildings, each of which has a different server name. All table names and fields are universal.
I have the server names, universal ID and PW, database name, network name, and port used to connect to the SQL servers. All are the same for all buildings, except server name. So only the server name will need to be changed in the connection string. All of this info is saved in a table.
I've read several posts from stack and other sites but cant quite get anything to work.
What I want to be able to do is to use a combo box to select the building name that I want to connect to, and have that combo box output the server name for that building. (This I know how to do within the properties window) And then have the VBA code update the linked tables to the new server.
What I do not know/understand is how to pass the combo box output into a VBA variable to be used in the connection string, nor write the code to update the connection string. Most of what I have found has been how to change DSN to DSN-less, or change specific tables. I want to update all the linked tables at once.
Id like to understand generally how the code works, so any ELI5 comments are greatly appreciated.
Here is a function to create a connection string:
Public Function ConnectionString( _
ByVal Hostname As String, _
ByVal Database As String, _
ByVal Username As String, _
ByVal Password As String) _
As String
' Create ODBC connection string from its variable elements.
' 2016-04-24. Cactus Data ApS, CPH.
Const AzureDomain As String = ".windows.net"
Const OdbcConnect As String = _
"ODBC;" & _
"DRIVER=SQL Server Native Client 11.0;" & _
"Description=Your Application;" & _
"APP=Microsoft® Access;" & _
"SERVER={0};" & _
"DATABASE={1};" & _
"UID={2};" & _
"PWD={3};" & _
"Trusted_Connection=No;"
Dim FullConnect As String
If Right(Hostname, Len(AzureDomain)) = AzureDomain Then
' Azure SQL connection.
' Append servername to username.
Username = Username & "#" & Split(Hostname)(0)
End If
FullConnect = OdbcConnect
FullConnect = Replace(FullConnect, "{0}", Hostname)
FullConnect = Replace(FullConnect, "{1}", Database)
FullConnect = Replace(FullConnect, "{2}", Username)
FullConnect = Replace(FullConnect, "{3}", Password)
ConnectionString = FullConnect
End Function
And here is a function to relink the tables and pass-trough queries:
Public Function AttachSqlServer( _
ByVal Hostname As String, _
ByVal Database As String, _
ByVal Username As String, _
ByVal Password As String) _
As Boolean
' Attach all tables linked via ODBC to SQL Server or Azure SQL.
' 2016-04-24. Cactus Data ApS, CPH.
Const cstrQuery1 As String = "_Template"
Const cstrQuery2 As String = "_TemplateRead"
Const cstrQuery3 As String = "VerifyConnection"
Const cstrDbType As String = "ODBC"
Const cstrAcPrefix As String = "dbo_"
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Dim strName As String
On Error GoTo Err_AttachSqlServer
Set dbs = CurrentDb
strConnect = ConnectionString(Hostname, Database, Username, Password)
For Each tdf In dbs.TableDefs
strName = tdf.Name
If Asc(strName) <> Asc("~") Then
If InStr(tdf.Connect, cstrDbType) = 1 Then
If Left(strName, Len(cstrAcPrefix)) = cstrAcPrefix Then
tdf.Name = Mid(strName, Len(cstrAcPrefix) + 1)
End If
tdf.Connect = strConnect
tdf.RefreshLink
Debug.Print Timer, tdf.Name, tdf.SourceTableName, tdf.Connect
DoEvents
End If
End If
Next
dbs.QueryDefs(cstrQuery1).Connect = strConnect
dbs.QueryDefs(cstrQuery2).Connect = strConnect
dbs.QueryDefs(cstrQuery3).Connect = strConnect
Debug.Print "Done!"
AttachSqlServer = True
Exit_AttachSqlServer:
Set tdf = Nothing
Set dbs = Nothing
Exit Function
Err_AttachSqlServer:
Call ErrorMox
Resume Exit_AttachSqlServer
End Function
This should get you going.

How to refresh linked tables if Access disconnects from MySQL database server?

So, I need a way to refresh the linked tables in my Access Database so that if the Internet disconnects for some reason the ODBC won't have an error when a query is sent and simply refreshes to see if the query can be sent again. However, the Access database doesn't reconnect for some reason when the Internet comes back up. Is there a way, in VBA, to refresh the linked tables if this does happen?
Would the .RefreshLink method do what you want?
There's an example here: https://msdn.microsoft.com/en-us/library/office/ff198349.aspx
Another solution would be to reconnect to the remote database calling this function.
Function ConnectODBC(ByVal strDsn As String, ByVal strDatabase As String, ByVal strUserName As String, ByVal strPassword As String)
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Dim strConnection As String
strConnection = "ODBC;DSN=" & strDsn & ";" & _
"DATABASE=" & strDatabase & ";" & _
"UID=" & strUserName & ";" & _
"PWD=" & strPassword
Set qdf = CurrentDb.CreateQueryDef("")
With qdf
.Connect = strConnection
.SQL = "SELECT 1;"
End With
Set rst = qdf.OpenRecordset(dbOpenSnapshot, dbSQLPassThrough)
ConnectODBC = True
Set rst = Nothing
Set qdf = Nothing
End Function

Open connection to MySQL from VBA Excel 2007

I got this error when try to connect Excel and MySQL using ODBC
DataSource name not found and no default driver specified
Here is my VBA code:
Sub test123()
' Connection variables
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String
' Table action variables
Dim i As Long ' counter
Dim sqlstr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim rs As ADODB.Recordset
Dim vtype As Variant
'----------------------------------------------------------------------
' Establish connection to the database
server_name = "127.0.0.1" ' Enter your server name here - if running from a local computer use 127.0.0.1
database_name = "smss" ' Enter your database name here
user_id = "root" ' enter your user ID here
password = "" ' Enter your password here
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 5.2a Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
' Extract MySQL table data to first worksheet in the workbook
GoTo skipextract
Set rs = New ADODB.Recordset
sqlstr = "SELECT * FROM inbox" ' extracts all data
rs.Open sqlstr, conn, adOpenStatic
With Sheet1(1).Cells ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
skipextract:
End Sub
I've added references (tools-reference)
The ODBC driver also has been installed.
What is actually wrong? Thank you.
There are many articles on this site describing similar problems. In particular, there were a couple of pointers in this link that rang true.
In your code above, one line in particular struck me as troublesome:
Dim conn As New ADODB.Connection
followed lower down by
Set conn = New ADODB.Connection
The second overrides the first in a way that makes me, for one, uncomfortable - although I can't tell you exactly what is wrong, except that you're creating TWO New Connections...
Try that - and the other fixes recommended in the linked article. Good luck.
maybe this might help you/others:
Add this reference to your project: Microsoft ActiveX Data object 2 (or any higher version you have)
Throw this code into a module and save it:
Edit the server details in this module.
'---------------------------------------------------------------------------------------
' Module : Mod_Connection
' Author : Krish km, xkrishx.wordpress.com
' Date : 27/08/2014
' Purpose : use this for build mysql connectin string.
' Declaration: © Krish KM, 2014.
' : Free to modify and re-use as long as a clear credit is made about the orgin of the code and the link above
' : This script is distributed in the hope that it will be useful,
' : but WITHOUT ANY WARRANTY; without even the implied warranty of
' : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' : GNU General Public License for more details.
'---------------------------------------------------------------------------------------
Option Explicit
Public ConnectionString As String
Private Const HKEY_LOCAL_MACHINE = &H80000002
Public Function GET_CURRENT_DRIVER() As String
'---------------------------------------------------------------------------------------
' Procedure : GET_CURRENT_DRIVER
' Author : Krish km
' Date : 27/08/2014
' Purpose : This function returns available mysql odbc drivers found in the registry. You could search by MySQL ODBC and get the first result
' : but I prefer prioritize the drivers i would like to yield first
'---------------------------------------------------------------------------------------
'
If FIND_ODBC_DRIVER(GET_ODBC_DRIVER_NAMES, "MySQL ODBC 5.2 Unicode Driver") <> "" Then
GET_CURRENT_DRIVER = "MySQL ODBC 5.2 Unicode Driver"
ElseIf FIND_ODBC_DRIVER(GET_ODBC_DRIVER_NAMES, "MySQL ODBC 5.2w Driver") <> "" Then
GET_CURRENT_DRIVER = "MySQL ODBC 5.2w Driver"
Else
GET_CURRENT_DRIVER = FIND_ODBC_DRIVER(GET_ODBC_DRIVER_NAMES, "MySQL ODBC")
End If
End Function
Public Function GET_CONNECTION_STRING() As String
'---------------------------------------------------------------------------------------
' Procedure : GET_CONNECTION_STRING
' Author : Krish KM
' Date : 27/08/2014
' Purpose : Returns MySQL connection string
'---------------------------------------------------------------------------------------
'
If Not ConnectionString = vbNullString Then
GET_CONNECTION_STRING = ConnectionString
Else
Dim Driver As String
Dim mDatabase As String
Dim mServer As String
Dim mUser As String
Dim mPassword As String
Dim mPort As Integer
mDatabase = "" ' DB name
mServer = "" ' Server name
mUser = "" ' DB user name
mPassword = "" ' DB user password
mPort = 3306 ' DB port
Driver = GET_CURRENT_DRIVER
If Driver = "" Then
Err.Raise 1, Err.Source, "MYSQL ODBC drivers are missing"
Exit Function
End If
ConnectionString = "DRIVER={" & Driver & "};PORT=" & mPort & ";DATABASE=" & mDatabase & ";SERVER={" & mServer & "};UID=" & mUser & ";PWD={" & mPassword & "};"
GET_CONNECTION_STRING = ConnectionString
End If
End Function
Public Function GET_ODBC_DRIVER_NAMES()
'---------------------------------------------------------------------------------------
' Procedure : GET_ODBC_DRIVER_NAMES
' Author : Krish KM
' Date : 27/08/2014
' Purpose : Checks in the registry for any odbc driver signatures and returns the collection
'---------------------------------------------------------------------------------------
'
Dim strComputer As String, strKeyPath As String
Dim objRegistry As Object, arrValueNames, arrValueTypes
strComputer = "."
strKeyPath = "SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers"
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
objRegistry.EnumValues HKEY_LOCAL_MACHINE, strKeyPath, arrValueNames, arrValueTypes
GET_ODBC_DRIVER_NAMES = arrValueNames
End Function
Public Function FIND_ODBC_DRIVER(ByVal iArr, ByVal sValue) As String
'---------------------------------------------------------------------------------------
' Procedure : FIND_ODBC_DRIVER
' Author : Krish KM
' Date : 27/08/2014
' Purpose : Simple array function to check if a specific value exists. if yes return the value if not return empty string
'---------------------------------------------------------------------------------------
'
FIND_ODBC_DRIVER = ""
Dim iValue As Variant
For Each iValue In iArr
If iValue = sValue Then
FIND_ODBC_DRIVER = iValue
Exit Function
End If
Next
End Function
Copy/modify this function on your excel sheet button/macro:
update the SQL_GET statement as per your request/sql call.
Sub Retrieve_EMP_Details()
'---------------------------------------------------------------------------------------
' Procedure : Retrieve_EMP_Details
' Author : Krish KM
' Date : 27/08/2014
' Purpose : connects to the database and retrieves employee details.
'---------------------------------------------------------------------------------------
'
'Connection variables
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As ADODB.Recordset
'Get connection string and connect to the server
On Error GoTo ERR_CONNECTION:
conn.ConnectionString = GET_CONNECTION_STRING ' trap additional error if you want
conn.Open
'Preparing SQL Execution
Dim SQL_GET As String
SQL_GET = "SELECT * FROM tbl_employee" ' extracts all data
cmd.Name = "EMPSearch"
cmd.ActiveConnection = conn
cmd.CommandText = SQL_GET
'Execute SQL
Set rs = cmd.Execute
On Error GoTo ERR_READ_SQL
If Not rs.EOF Then
With Sheets(1).Cells ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
Else
Sheets(1).Range("A1").value = "No records found :("
End If
EXIT_SUB:
On Error Resume Next
Set conn = Nothing
Set cmd = Nothing
Set rs = Nothing
Exit Sub
ERR_CONNECTION:
MsgBox "Sorry unable to connect to the server.." & vbNewLine & "Connection string: " & GET_CONNECTION_STRING & vbNewLine & "System Msg: " & Err.Description
GoTo EXIT_SUB
ERR_READ_SQL:
MsgBox "Sorry unable read/wite results on the sheet.." & vbNewLine & "System Msg: " & Err.Description
GoTo EXIT_SUB
End Sub
If you have ODBC drivers installed, all the server details provided, SQL statement adjusted. just execute the sub_routine {Retrieve_EMP_Details} and you should be able to see the results in sheet(1)
Hope this helps and enjoy :)
Krish KM