Import data from web site in MS Access - ms-access

I want to write an import function for importing data from a website into a ms access database. The original data is stored in a mysql database and is available via a remote text file (csv). So all I want is to access this remote file and read it in vba. The code I use is below, but it seems that references are missing. Don't know which reference ActiveXperts.Http needs. Could anybody help?
Thx
Steve
Dim objHttp
Dim strUrl
Dim strData
' Create a HTTP instance
Set objHttp = CreateObject("ActiveXperts.Http")
' Write some information to console
MsgBox "ActiveSocket " & objHttp.Version & " demo."
MsgBox "Expiration date: " & objHttp.ExpirationDate & vbCrLf
Do
strUrl = InputBox("Enter a URL", "Input", "www.activexperts.com/products")
Loop Until strUrl <> ""
objHttp.LogFile = "C:\HttpLog.txt"
objHttp.Connect (strUrl)
If (objHttp.LastError <> 0) Then
MsgBox "Error " & objHttp.LastError & ": " & objHttp.GetErrorDescription(objHttp.LastError)
Else
strData = objHttp.ReadData
If (objHttp.LastError <> 0) Then
MsgBox "Error " & objHttp.LastError & ": " & objHttp.GetErrorDescription(objHttp.LastError)
Else
MsgBox strData
End If
objHttp.Disconnect
MsgBox "Disconnect."
End If
MsgBox "Ready."

This tutorial says that it needs ActiveSocket 2.4 Type Library.
(the tutorial is for VB 5/6 and not VBA, but the reference stuff should be exactly the same)

Related

Method 'LoadFromText' of Object 'Application' Failed

So I've been at days now trying to solve this bug. After having all functions for Access objects exported, removing binary data from specified fields, and importing Access objects to fresh database, this is the error I'm still having issues with.
Run-time error '-2147417851 (80010105)':
Method 'LoadFromText' of object '_Application' failed.
Edit:
As requested, here is the full function code that handles the import. The error is caused in the "Form" LoadFromText line:
Private Sub Setup_New_Database_File(ByVal srcFileName As String, ByVal destPath As String, ByVal txtDumpPath As String)
' srcFileName: Name of the old datbase file
' destPath: Destination path of where new Access object is created at
' txtDumpPath: Directory housing all exported Access text files
Dim accApp As Access.Application
Set accApp = New Access.Application
' Creating a new Access object
iDate = " (" & Format(Date, "mm-dd-yy") & ")"
newDBName = destPath & srcFileName & iDate & ".accdb"
' Auto-delete existing file with same name
If Dir(newDBName) <> "" Then
SetAttr newDBName, vbNormal
Kill newDBName
End If
With accApp
.DBEngine.CreateDatabase newDBName, DB_LANG_GENERAL, dbVersion120
.OpenCurrentDatabase (newDBName)
.Visible = False
.Echo False ' Hide any other Access windows apart from current
.UserControl = False
' --------------------------------------------------------------------------------------------
'On Error GoTo Err_SetupNewDatabaseFile
' Iterate through the directory containing textfile versions of Access objects created previously from SaveAsText,
' and write back to new Access DB file instance
Dim dirObject As Variant
fp = txtDumpPath & "\" & "*.txt"
dirObject = Dir(fp)
Do While Len(dirObject) > 0
cFilePath = txtDumpPath & "\" & dirObject
' Extract the text file type: [Form_, Module_, Query_, Report_, Script_, Table_]
' Every naming convention only has one "_" character.
fTarget = InStr(dirObject, "_")
fStart = fTarget + 1
cfLength = Len(dirObject)
cFileName = Mid(dirObject, fStart, cfLength) ' E.G: objectname.txt
pTarget = InStrRev(cFileName, ".")
pEnd = pTarget - 1
If dirObject = "Database Linked Tables.txt" Then
' Our Linked Tables are large in data, so opted to add them in via connection.
Dim fso As Object, oFile As Object, cLine As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.OpenTextFile(cFilePath, ForReading, False)
Do Until oFile.AtEndOfStream
cLine = oFile.ReadLine
If cLine = "" Or cLine = Null Then
GoTo Next_Iteration 'Moving on...
Else
' Need to check for Driver sources
If cLine = "xResults Local" And Special_Character_Match(cLine, "xResults") = True Then
tPath = DLookup("[Database Path]", "[Tables List]", "[Table Name] = 'xResults'")
accApp.DoCmd.TransferDatabase acLink, "Microsoft Access", tPath, acTable, cLine, cLine, False
ElseIf cLine <> "" Or cLine <> Null Then
' Local vs ODBC:::
option1_path = DLookup("[Database Path]", "[Tables List]", "[Table Name] = '" & cLine & "'")
option2_path = DLookup("[Connect]", "[Tables List]", "[Table Name] = '" & cLine & "'")
If option1_path <> "" Or option1_path <> Null Then
accApp.DoCmd.TransferDatabase acLink, "Microsoft Access", option1_path, acTable, cLine, cLine, False
ElseIf option2_path <> "" Or option2_path <> Null Then
option2_source = DLookup("[MySQL Name]", "[Tables List]", "[Table Name] = '" & cLine & "'")
option2_setTableNameTo = cLine
connectString = "ODBC;" & option2_path & ";"
accApp.DoCmd.TransferDatabase acLink, "ODBC Database", connectString, acTable, option2_source, option2_setTableNameTo
End If
End If
End If 'End of cLine = "" check
Next_Iteration:
Loop
oFile.Close
Set fso = Nothing
Set oFile = Nothing
'-----------------------------------------------------------------------------------------------------------------
Else
' Add all textfiles in txtdump dir to new Access file
accObjectType = Left(dirObject, fTarget - 1) ' E.G: Form
accObjectName = Left(cFileName, pEnd) ' E.G: objectname
' Reconvert accObjectName to its original state
Select Case accObjectType
Case "Form"
MsgBox "File Name: [" & accObjectName & "], Form Name: [" & cFilePath & "]"
'On Error Resume Next
accApp.LoadFromText acForm, accObjectName, cFilePath
Case "Module"
accApp.LoadFromText acModule, accObjectName, cFilePath
Case "Query"
accApp.LoadFromText acQuery, accObjectName, cFilePath
Case "Report"
accApp.LoadFromText acReport, accObjectName, cFilePath
Case "Script"
accApp.LoadFromText acMacro, accObjectName, cFilePath
Case "Table"
accApp.DoCmd.TransferText acImportDelim, , accObjectName, cFilePath, True
End Select
End If
' Next file iteration
NextFileIteration:
dirObject = Dir
Loop
End With
' ---------------------------------------------------------------------------------------------
' Variable Cleanup
accApp.Echo True
accApp.Quit
Set accApp = Nothing
End Sub
And where an example Form text file (with the necessary data removed) is here
Where to differentiate the objects, files in cFilePath follow "\dir...\Form_FormName.txt" format, while accObjectName is just "FormName". The issue I'm having is importing Access forms.
Things I have tried:
- I have removed the "NoSaveCTIWhenDisabled =1" lines from the form files, since in old mdb formats this was causing import issues. (Even with this line on still caused import issues)
- I have also tried removing all blank lines from the text files, in case the command had issues with reading them.
While a small subset of form objects to get imported, not all of them do, resulting in this error. Checking the files themselves to see why, I can't make sense of them since the format looks relatively the same for all of them. What would be a reason for this automation error to occur? All other export/parsing functions seem to run fine...

MS Access VBA Reference

I have this database and it was working perfect, but today it started hating me. I started getting a Compile error: Can't find project or library. I looked around and found that when using the front end on a different computer, under VBA and references, it was missing a reference for Microsoft Word 15.0 Object Library.
My computer I have the Microsoft Word 16.0 Object Library checked. How can I get this to work on other computers with 15.0 and 16.0?
Here is the code
Private Sub cmd_LocateFile_Click()
On Error GoTo Error_Handler
Dim sFile As String
Dim sFolder As String
Dim ID As Long
Dim sTarget As String
sFile = FSBrowse("", msoFileDialogFilePicker, "All Files (*.*),*.*")
If sFile <> "" Then
sFolder = ("\\aiowima23fp1\Ecological Sciences and Engineering\Cultural Resources\New - Cultural Resources Request Database") & "\" & sAttachmentFolderName & "\"
If FolderExist(sFolder) = False Then MkDir (sFolder)
ID = RequestID_FK ' Set current record id.
sTarget = sFolder & CStr(ID) & "-" & GetFileName(sFile)
If CopyFile(sFile, sFolder & GetFileName(sTarget)) = True Then
Me!FullFileName.Value = sTarget
Else
End If
End If
Error_Handler_Exit:
On Error Resume Next
Exit Sub
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: " & sModName & "\cmd_LocateFile_Click" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Sub
Adding references to Word during development has the advantage to be able to use strongly typed word objects and thus being able to take advantage of IntelliSense. But these references are, as you have experienced, sensible to versioning. Therefore, I suggest you remove the reference to Word once development is achieved. You will also have to replace all Word-related types by Object, i.e. use late binding. This makes the application more robust with respect to versioning.
You can get an existing Word instance which is already open or open a new one with this code snippet, without any references to Word DLLs.
Public Function GetWordApplication() As Object
'Gets an active Word application or opens a new Word instance.
'Raises Error No. 8 if word cannot be opened.
On Error Resume Next
'Find existing instance of Word
Set GetWordApplication = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Not found, create new instance.
Set GetWordApplication = CreateObject("Word.Application")
End If
'Following code is optional. You can instead test for Nothing at the call site
On Error Goto 0
If GetWordApplication Is Nothing Then
Err.Raise 8, "YourApp.GetWordApplication", "Word could not be opened."
End If
End Function

Output ADODB.RecordSet as JSON

I'm trying to change my application so that it outputs JSON instead of HTML when it makes an AJAX request for some data. I have an ADODB RecordSet. I need to loop through it row-by-row and add/change/remove different values. Then I need to take all the modified rows and response.write them as JSON. I'm using JSON2.asp so my application already supports JSON.parse & JSON.stringify but I can't get it to spit out the multi-dimensional array as JSON.
set rs = conn.execute(strQuery)
if Not rs.EOF Then
rsArray = rs.GetRows() 'This pulls in all the results of the RecordSet as a 2-dimensional array
columnCount = ubound(rsArray,1)
rowCount = ubound(rsArray,2)
For rowIndex = 0 to rowCount 'Loop through rows as the outer loop
rsArray(3,0) = "somethingelse"
Next 'Move on to next row if there is one
response.write JSON.stringify(rsArray) & " _______ "
End If
I just need to be able to go through the results of my database query, modify the results, and then output the modified results in JSON format. What's the right way to do this?
The JSON2.asp implementation doesn't have a "Load From Database" function which means you will have to implement something to convert the ADODB.Recordset to a JSON structure yourself.
If you are willing to use a different script there is an implementation by RCDMK on GitHub that does have a LoadRecordset() method, it's called JSON object class 3.5.3.
This makes loading data from an ADODB.Recordset really straightforward.
<!-- #include virtual="/jsonObject.class.asp" -->
<%
Response.LCID = 2057
'...
Dim rs: Set rs = conn.execute(strQuery)
Dim JSON: Set JSON = New JSONobject
Call JSON.LoadRecordset(rs)
Call Response.Clear()
Response.ContentType = "application/json"
Call JSON.Write()
%>
Code has been tested using a disconnected recordset, the ... here denote assumed code to setup your recordset, connection etc
It's worth noting you could write this yourself, it's not a huge leap to loop through an ADODB.Recordset and build a JSON string. However, I would argue against for a few reasons;
It is a time-consuming exercise.
Very easy to miss something (like checking for numeric data types, when generating output).
Depending on how it is coded can make it awkward to maintain (For example, if not injecting property names directly from the recordset and choosing to "hardcode" them instead).
Why reinvent the wheel ? There are a lot of public implementations in the wild that deal with the issues raised here. Admittedly, some are better than others, but it takes five minutes to include them and give it a try.
Just for completeness here is my local test code using a disconnected recordset
<!-- #include virtual="/jsonObject.class.asp" -->
<%
Call init()
Sub init()
Dim fields: fields = Array(Array("title", adVarChar, 50), Array("firstname", adVarChar, 50), Array("lastname", adVarChar, 50), Array("age", adInteger, 4))
Dim rs: Set rs = Server.CreateObject("ADODB.Recordset")
Call InsertRow(rs, fields, Array("Mr", "Joe", "Bloggs", 31))
Call InsertRow(rs, fields, Array("Mr", "John", "Smith", 42))
Response.LCID = 2057
Dim JSON: Set JSON = New JSONobject
Call JSON.LoadRecordset(rs)
Call Response.Clear()
Response.ContentType = "application/json"
Call JSON.Write()
End Sub
Sub InsertRow(ByVal rs, fields, values)
With rs
If rs.State <> adStateOpen Then
For Each fld In fields
Call .Fields.Append(fld(0), fld(1), fld(2))
Next
.CursorLocation = adUseClient
.CursorType = adOpenDynamic
Call .Open()
End If
Call .AddNew()
For i = 0 To UBound(fields, 1)
.Fields(fields(i)(0)).Value = values(i)
Next
Call .Update()
Call .MoveFirst()
End With
End Sub
%>
Output:
{"data":[{"title":"Mr","firstname":"Joe","lastname":"Bloggs","age":31},{"title":"Mr","firstname":"John","lastname":"Smith","age":42}]}
Here ya go. This works for me.
set rs = conn.execute(strQuery)
c=0
Response.write "["
Do Until rs.eof
'Assign variables here with whatever you need to change
title = rs(0)
fName = rs(1)
lName = rs(2)
empID = rs(3)
With Response
if c > 0 then .write ", "
.write "{" & chr(34) & "Title" & chr(34) & " : " & chr(34) & title & chr(34) & ", " & chr(34) & "FirstName" & chr(34) & " : " & chr(34) & fName & chr(34) & ", "
.write chr(34) & "LastName" & chr(34) & " : " & chr(34) & lName & chr(34) & ", " & chr(34) & "EmpID" & chr(34) & " : " & chr(34) & empID & chr(34) & "}"
End With
c = c + 1
rs.MoveNext
Loop
Response.write "]"
This will write your JSON object directly to the page.
try setting content-type to "application/json" on top of your asp page.
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
Option Explicit
Response.Buffer=True
Response.ContentType="application/json"
Response.Charset="utf-8"
'' rest of your code.. your db operations
'' response write your json
%>

Force a zip to open unzip to specific location

I'm making a very basic data entry and database system application using excel (for bulk data entry) and Access (to house the data). I play to distribute it as a zip file. In order for it to work I need the file structure to remain unchanged and to unzip to c:/ drive. Is there anyway to force a zip file to unzip to a specific location?
The reason I need this is to automate the uploading of entered data. As far as I know in Access VBA you have to specify full filepaths in VBA to import data.
* Update
Thanks to Remou for getting me out of the woods. Just for posterity's sake this is how I solved it. not the prettiest code but it does the job. First the import function and then the export function.
Importing, a naming convention is still need for the files being uploaded but they can come from anywhere. That file name relates to the tables they will be stored in. At the back end of the excel sheets the data input sheet is split into two (Rec and Occ)
Code as follows:
Function importData_Click(Optional varDirectory As String, _
Optional varTitleForDialog As String) As String
Dim strFilter As String
Dim lngFlags As Long
Dim varFileName As String
Dim strFileName As String
Dim strTableName As String
Dim strColumnName As String
Dim The_Year As Long
Dim occNumber As Long
'Get combobox value and assign relavent values to occNumber
The_Year = Forms![Upload Data]!Year_Combo.value
'Ask the to check value
If MsgBox("Uploading " & The_Year & " data" & vbCrLf & "Continue?", VbMsgBoxStyle.vbYesNo) = 7 Then
Exit Function
End If
If The_Year = 2012 Then
occNumber = 1000
ElseIf The_Year = 2013 Then
occNumber = 2000
End If
' Specify that the chosen file must already exist,
' don't change directories when you're done
' Also, don't bother displaying
' the read-only box. It'll only confuse people.
lngFlags = ahtOFN_FILEMUSTEXIST Or _
ahtOFN_HIDEREADONLY Or ahtOFN_NOCHANGEDIR
If IsMissing(varDirectory) Then
varDirectory = ""
End If
If IsMissing(varTitleForDialog) Then
varTitleForDialog = ""
End If
strFilter = ahtAddFilterItem("Excel Files (*.xlsx)", "*.xlsx")
varFileName = ahtCommonFileOpenSave( _
openFile:=True, _
InitialDir:=varDirectory, _
Filter:=strFilter, _
Flags:=lngFlags, _
DialogTitle:=varTitleForDialog)
If Not IsNull(varFileName) Then
varFileName = TrimNull(varFileName)
End If
importData_Click = varFileName
'Sets filename
strFileName = Dir(varFileName)
'Sets TableName
strTableName = Left(strFileName, 4)
If IsNull(strFileName) Then
MsgBox "Upload cancelled"
Exit Function
End If
'Checks naming convetions of filenames
If strTableName Like "*MN" Or strTableName Like "*OP" Or strTableName Like "*DA" Or strTableName Like "*TR" Then
'Checks if data is Opportunistic
If strTableName Like "*OP" Then
strColumnName = "Year_" & strTableName
'Checks to see if that year's data already exists
If DLookup(strColumnName, strTableName & "_Rec", "" & strColumnName & " = " & The_Year & "") Then
MsgBox "2012 data is already present"
ElseIf DLookup(strColumnName, strTableName & "_Rec", "" & strColumnName & " = " & The_Year & "") Then
MsgBox "2013 data is already present"
Else
'Uploads data to relevant table
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, strTableName & "_Rec", varFileName, True, "Rec_Prep$"
MsgBox "Upload successful"
End If
Exit Function
Else
strColumnName = "Occasion_" & strTableName
'Checks Occasions to see if that year exists
If DLookup(strColumnName, strTableName & "_Rec", "" & strColumnName & " = " & occNumber & "") Then
MsgBox "2012 data is already present"
ElseIf DLookup(strColumnName, strTableName & "_Rec", "" & strColumnName & " = " & occNumber & "") Then
MsgBox "2013 data is already present"
Else
'Uploads to Records table and Occasion table
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, strTableName & "_Occ", varFileName, True, "Occ_Prep$"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, strTableName & "_Rec", varFileName, True, "Rec_Prep$"
MsgBox "Upload successful"
End If
End If
Else
MsgBox "Your file is named incorrectly! & vbCrLf & Please refer to the Data Dictionary & vbCrLf & for correct naming conventions"
Exit Function
End If
'DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "BaMN_AllData", strSaveFileName
End Function
Private Function TrimNull(ByVal strItem As String) As String
Dim intPos As Integer
intPos = InStr(strItem, vbNullChar)
If intPos > 0 Then
TrimNull = Left(strItem, intPos - 1)
Else
TrimNull = strItem
End If
End Function
Then the export uses the names of command buttons (that match table names) to export to wherever the user wants:
Dim queryYear As Variant
'Function to export data to location of users choice. Query name is automatically detected from the control button used
'Year is derived from the combobox value on [Extract Data] form, null value defaults to all years.
Function exportData_Click()
Dim strFilter As String
Dim strSaveFileName As String
Dim The_Year As Variant
Dim ctlCurrentControl As Control
Dim queryName As String
'Get the name of the control button clicked (corresponds to query name to be run)
Set ctlCurrentControl = Screen.ActiveControl
queryName = ctlCurrentControl.Name
'Get combobox value and assign relavent values to The_Year
The_Year = Forms![Extract Data]!Extract_Year.value
'Change the year from a variant to what we need in the SQL
If The_Year Like "20*" Then
The_Year = CInt(The_Year)
MsgBox The_Year & "Data Type = " & VarType(The_Year)
Else: The_Year = "*"
MsgBox The_Year & "Data Type = " & VarType(The_Year)
End If
'Set queryYear variable
setYear (The_Year)
'Check the variable is correct
'MsgBox getYear()
'Open the Save as Dialog to choose location of query save
strFilter = ahtAddFilterItem("Excel Files (*.xlsx)", "*.xlsx")
strSaveFileName = ahtCommonFileOpenSave( _
openFile:=False, _
Filter:=strFilter, _
Flags:=ahtOFN_OVERWRITEPROMPT Or ahtOFN_READONLY)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, queryName, strSaveFileName
End Function
'Function to set queryYear used in data extraction queries
Public Function setYear(The_Year As Variant)
queryYear = The_Year
End Function
'Function to get queryYear used in data extraction queries
Function getYear()
getYear = queryYear
End Function
It should be noted that the file save and file open code sections are not mine. They come from Ken Getz and the whole code can be found here:
http://access.mvps.org/access/api/api0001.htm
It would be better to use the application path ( eg currentproject.Path ) or to ask the user to specify a location for the data store rather than to try to force an install at a location that may not be available to the user. There is no need at all to hard-code paths. In Access, you can store information relevant to the project in a table, including the data path. You can look up MS Access from Excel.

ODBC call failed error when an access table is opened

I have linked the sql server tables to ms access so that I can use ms access as the front end.I was able to access the tables from access, until I run into an error ODBC call failed when I tried to open one of the tables. There was no problem with the other tables. Actually I have changed a column name in sql server after creating a link. Is this the problem? I am really worried about this as I was about to use access as a front-end for my future purposes.
When you link to a remote table, Access stores metadata about that table. When you later change the table structure, the metadata doesn't get updated to capture the change.
Delete the link. Then recreate the link. That way the metadata will be consistent with the current version of the table.
Yes changing the column name after linking the table is most likely causing your failure. Is it is now trying to pull data from a column that no longer exists. You will need to relink the table. You can programatically link tables in access. We do that in may of our access applications and drive the tables that need to be linked from a local access table.
Public Sub LinkODBCTables()
Dim objRS As DAO.Recordset
Dim objTblDef As DAO.TableDef
Dim strTableName As String
Dim strAliasName As String
Dim strDSN As String
Dim lngTblCount As Long
Set objRS = CurrentDb.OpenRecordset( _
" select TableName," & _
" AliasName," & _
" DSN," & _
" DatabaseName," & _
" Development_DSN," & _
" UniqueIndexCol" & _
" from tblODBCLinkedTables " & _
" order by TableName", dbOpenSnapshot)
While Not objRS.EOF
' Check to see if we already have this linked tableDef
' We don't care if it is not actually in there
strTableName = objRS.Fields("TableName")
If Not IsNull(objRS.Fields("AliasName")) Then
strAliasName = objRS.Fields("AliasName")
Else
strAliasName = strTableName
End If
If DEV_MODE Then
strDSN = objRS.Fields("Development_DSN")
Else
strDSN = objRS.Fields("DSN")
End If
On Error Resume Next
CurrentDb.TableDefs.Delete strAliasName
If Err.Number <> 0 And _
Err.Number <> 3265 Then ' item not found in collection
Dim objError As Error
MsgBox "Unable to delete table " & strAliasName
MsgBox Err.Description
For Each objError In DBEngine.Errors
MsgBox objError.Description
Next
End If
On Error GoTo 0
Set objTblDef = CurrentDb.CreateTableDef(strAliasName)
objTblDef.Connect = g_strSQLServerConn & _
"DSN=" & strDSN & _
";DATABASE=" & objRS.Fields("DatabaseName") & _
";UID=" & g_strSQLServerUid & _
";PWD=" & g_strSQLServerPwd
objTblDef.SourceTableName = strTableName
On Error Resume Next
CurrentDb.TableDefs.Append objTblDef
If Err.Number <> 0 Then
Dim objErr As DAO.Error
For Each objErr In DBEngine.Errors
MsgBox objErr.Description
Next
End If
On Error GoTo 0
' Attempt to create a uniqe index of the link for updates
' if specified
If Not IsNull(objRS.Fields("UniqueIndexCol")) Then
' Execute DDL to create the new index
CurrentDb.Execute " Create Unique Index uk_" & strAliasName & _
" on " & strAliasName & "(" & objRS.Fields("UniqueIndexCol") & ")"
End If
objRS.MoveNext
Wend
objRS.Close
End Sub
We are using a single SQLServer login for our access applications so the g_strSQLServerUID and g_strSQLServerPwd are globals that contain that info. You may need to tweek that for your own needs or integrated security. We are setting up two DSNs one for production and the other for development. The DEV_MODE global controls wich set of DSNs are linked. You can call this code from a startup macro or startup form. It will deleted the old link and create a new link so you always have the most up to date schema.