I’m somewhat ashamed to admit it, but my ADO skill are rather limited (and even that is an understatement). Can someone show me the correct syntax for opening a connection to another database? (That is, a different database than the CurrentProject.)
![]() |
Patch reliability is unclear. Unless you have an immediate, pressing need to install a specific patch, don't do it. |
SIGN IN | Not a member? | REGISTER | PLUS MEMBERSHIP |
-
ADO code needed (Any)
Home » Forums » AskWoody support » Productivity software by function » MS Access and database help » ADO code needed (Any)
- This topic has 10 replies, 3 voices, and was last updated 21 years, 10 months ago.
AuthorTopicWSMarkLiquorman
AskWoody LoungerJune 26, 2003 at 11:42 pm #389685Viewing 0 reply threadsAuthorReplies-
WSMarkD
AskWoody LoungerJune 27, 2003 at 12:59 am #689294This is a simple example of opening a connection to Northwind.mdb from another database:
Public Sub adoTestConnection()
On Error GoTo Err_HandlerDim rst As ADODB.Recordset
Dim cnn As ADODB.Connection
Dim strAppPath As String
Dim strCnn As String
Dim strSQL As String
Dim strMsg As String‘ If db is secured use this syntax:
‘ strCnn = “Provider=Microsoft.Jet.OLEDB.4.0;” & _
‘ “User ID=MyUserName;” & _
‘ “Password=MyPwd;” & _
‘ “Data Source=” & strAppPath & “MyApp.mdb;” & _
‘ “Jet OLEDB:System database=” & strAppPath & “MyApp.mdw;”‘ If db is not secured:
strCnn = “Provider=Microsoft.Jet.OLEDB.4.0;” & _
“Data Source=C:Program FilesMicrosoft OfficeOffice10SamplesNorthwind.mdb;”strSQL = “SELECT * FROM ORDERS;”
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordsetcnn.ConnectionString = strCnn
cnn.Open
rst.Open strSQL, cnn, adOpenStatic, adLockOptimistic
‘ Test:
strMsg = “There are ” & rst.RecordCount & ” records in the Orders table.”
MsgBox strMsg, vbInformation, “RECORD COUNT”rst.Close
cnn.CloseExit_Sub:
Set cnn = Nothing
Set rst = Nothing
Exit Sub
Err_Handler:
Select Case Err.Number
Case 0
Resume Exit_Sub
Case Else
strMsg = “Error No ” & Err.Number & “: ” & Err.Description
MsgBox strMsg, vbExclamation, “ADO CONNECTION ERROR”
Resume Exit_Sub
End SelectEnd Sub
Note if other db is secured you will need to provide valid username & password & specify path to workgroup file to open a connection, as shown in commented out block. This example opens read-only recordset. You’ll need to modify the rst.Open statement depending on what type of recordset you need – the ADO Help files may provide some guidance on correct arguments to use. For example, for an updatable recordset you’d use adOpenDynamic in place of adOpenStatic for CursorType argument. If updating records much of the syntax is similar (or identical to) DAO equivalent (except, as I usually forget, ADO has no “Edit” method….)
HTH
-
WSMarkLiquorman
AskWoody LoungerJune 27, 2003 at 1:20 am #689302 -
WSMarkLiquorman
AskWoody LoungerJune 27, 2003 at 1:44 am #689308I seem to be having some problems. Here is the function I got from MSKB. It works fine for a table within the same database. But from my Frontend database, I need to manipulate the autonumbers in tables in the Backend. So right now I’m hung up on that “Set cnn = CurrentProject.Connection” line of code.
Function ChangeSeed(strTbl As String, strCol As String, lngSeed As Long) As Boolean
‘You must pass the following variables to this function.
‘strTbl = Table containing autonumber field
‘strCol = Name of the autonumber field
‘lngSeed = Long integer value you want to use for next AutoNumber.Dim cnn As ADODB.Connection
Dim cat As New ADOX.Catalog
Dim col As ADOX.Column‘Set connection and catalog to current database.
Set cnn = CurrentProject.Connection
cat.ActiveConnection = cnnSet col = cat.Tables(strTbl).Columns(strCol)
col.Properties(“Seed”) = lngSeed
cat.Tables(strTbl).Columns.Refresh
If col.Properties(“seed”) = lngSeed Then
ChangeSeed = True
Else
ChangeSeed = False
End If
Set col = Nothing
Set cat = Nothing
Set cnn = NothingEnd Function
-
WScharlotte
AskWoody LoungerJune 27, 2003 at 2:14 am #689321Mark,
If the table is in the backend database, you need to make a connection to manipulate the table’s design there. So you can’t use the CurrentProject.Connection approach, you have to build the full connection. There’s an example in on-line help of using the Columns Collection in ADOX that ;might be helpful to you. And what kind of table is the backend, because “seed” isn’t a property exposed by the Jet OLE DB provider?
-
WSMarkLiquorman
AskWoody Lounger
-
-
WSMarkD
AskWoody LoungerJune 27, 2003 at 2:57 am #689328I usually only use ADOX with Current Project. Here is an example of opening connection to other than CurrentProject for data definition purposes:
Public Sub adoCreateNewTable()
On Error GoTo Err_HandlerDim cnn As ADODB.Connection
Dim cat As ADOX.Catalog
Dim tbl As ADOX.Table
Dim strCnn As String
Dim strMsg As StringSet cnn = New ADODB.Connection
Set cat = New ADOX.Catalog
Set tbl = New ADOX.TablestrCnn = “Provider=Microsoft.Jet.OLEDB.4.0;” & _
“Data Source=C:Program FilesMicrosoft OfficeOffice10SamplesNorthwind.mdb;”cnn.ConnectionString = strCnn
cnn.Open strCnn
cat.ActiveConnection = cnntbl.Name = “Table1”
tbl.Columns.Append “PK_Field”, adInteger
tbl.Keys.Append “PrimaryKey”, adKeyPrimary, “PK_Field”
cat.Tables.Append tbl
cnn.CloseMsgBox “New table Table1 created in Northwind.mdb.”, vbInformation, “TEST MSG”
Exit_Sub:
Set cnn = Nothing
Set cat = Nothing
Set tbl = Nothing
Exit Sub
Err_Handler:
Select Case Err.Number
Case 0
Resume Exit_Sub
Case Else
strMsg = “Error No ” & Err.Number & “: ” & Err.Description
MsgBox strMsg, vbExclamation, “ADOX NEW TABLE ERROR”
Resume Exit_Sub
End SelectEnd Sub
Note the line highlighted in bold – when opening connection be sure to include connection string or this will not work! This example successfully created new table in Northwind.mdb. I’m afraid I don’t know if ADOX will let you reset “seed” for an AutoIncrement field.
HTH
-
WSMarkLiquorman
AskWoody Lounger -
WSMarkD
AskWoody LoungerJune 27, 2003 at 3:03 pm #689660Taking another look at this issue I had no problem setting connection to another .MDB (linked back table db, Northwind.mdb), tho’ resetting the AutoIncrement field proved to be tricky. Here is example of sub using ADO connection to reset an AutoIncrement (aka AutoNumber aka Identity aka Counter) field. Instead of using flaky ADOX to reset field attributes, used DDL SQL which is simpler & more reliable; use the ADO Connection Execute method to run the SQL statement:
Public Sub adoResetAutoIncrementField(ByRef strDbName As String, _
ByRef strTbl As String, _
ByRef strFld As String, _
ByRef lngSeedVal As Long, _
ByRef lngIncrementVal As Long)
On Error GoTo Err_HandlerDim cnn As ADODB.Connection
Dim strCnn As String
Dim strSQL As String
Dim strMsg As String‘ strDbName = “C:Program FilesMicrosoft OfficeOffice10SamplesNorthwind.mdb”
Set cnn = New ADODB.Connection
strCnn = “Provider=Microsoft.Jet.OLEDB.4.0;” & _
“Data Source=” & strDbName & “;”
cnn.ConnectionString = strCnn
cnn.Open strCnn‘ DDL syntax: “ALTER TABLE [Table1] ALTER COLUMN [RecordID] COUNTER (1000,4);”
strSQL = “ALTER TABLE [” & strTbl & “] ALTER COLUMN [” & strFld & “] ” & _
“COUNTER (” & lngSeedVal & “,” & lngIncrementVal & “);”cnn.Execute strSQL, , adCmdText Or adExecuteNoRecords
cnn.Close‘ Possible errors:
‘ strTbl = “Orders”, strFld = “OrderID”
‘ This generated error due to OrderID being used in relationships:
‘ Error No -2147467259: Cannot change field ‘OrderID’. _
It is part of one or more relationships. _
Also will get error if fld is defined as PK for table: _
Error No -2147467259: Invalid field data type.strMsg = “AutoNumber field ” & strFld & ” seed value has been reset to ” & _
lngSeedVal & ” in ” & strTbl & ” table. ” & _
“Increment Value reset to ” & lngIncrementVal & “.”
MsgBox strMsg, vbInformation, “TEST MSG”Exit_Sub:
Set cnn = Nothing
Exit Sub
Err_Handler:
Select Case Err.Number
Case 0
Resume Exit_Sub
Case Else
strMsg = “Error No ” & Err.Number & “: ” & Err.Description
Debug.Print strMsg
MsgBox strMsg, vbExclamation, “RESET AUTOINCREMENT FIELD ERROR”
Resume Exit_Sub
End SelectEnd Sub
Note that if the AutoNumber field was defined as a Primary Key, or involved in a relationship, was not able to alter field; got one of the error msg’s described in commented out block above. To be able to reset AutoNumber field defined as PK, it was necessary to first remove the PK index, then reset using DDL SQL Constraint clause like in this example:
ALTER TABLE Table1 ALTER COLUMN RecordID COUNTER (2000,5) CONSTRAINT PrimaryKey PRIMARY KEY;
If the AutoNumber field is also involved in relationships, it might be a bit convoluted to reset; you’d probably have to delete the relationships then re-create – not fun. I don’t know why you’d get an “Installable ISAM” error when trying to open ADO connection – that makes no sense!! The above code worked correctly on my system which is using AXP with Access 2000 file format for both FE & BE db’s.
HTH
-
WSMarkLiquorman
AskWoody Lounger -
WSMarkD
AskWoody LoungerJune 27, 2003 at 3:30 pm #689666PS – if ADO connection doesn’t work you can always resort to DAO as last resort, using Database object Execute method:
Public Sub daoResetAutoIncrementField(ByRef strDbName As String, _
ByRef strTbl As String, _
ByRef strFld As String, _
ByRef lngSeedVal As Long, _
ByRef lngIncrementVal As Long)
On Error GoTo Err_HandlerDim ws As DAO.Workspace
Dim db As DAO.Database
Dim strSQL As String
Dim strMsg As StringSet ws = DBEngine.Workspaces(0)
Set db = ws.OpenDatabase(strDbName)strSQL = “ALTER TABLE [” & strTbl & “] ALTER COLUMN [” & strFld & “] ” & _
“COUNTER (” & lngSeedVal & “,” & lngIncrementVal & “);”db.Execute strSQL
db.CloseSet ws = Nothing
Set db = NothingExample of use:
daoResetAutoIncrementField “C:Program FilesMicrosoft OfficeOffice10SamplesNorthwind.mdb”,”Table2″,”RecordID”,5000,5
This successfully reset AutoNumber field for Table2 (a linked table in current db) as shown in attached screen shot. Using DAO db Execute method seems to work same as ADO Connection Execute for executing a DDL SQL statement (you’ll get the same errors as well).
HTH
-
-
-
-
Viewing 0 reply threads -

Plus Membership
Donations from Plus members keep this site going. You can identify the people who support AskWoody by the Plus badge on their avatars.
AskWoody Plus members not only get access to all of the contents of this site -- including Susan Bradley's frequently updated Patch Watch listing -- they also receive weekly AskWoody Plus Newsletters (formerly Windows Secrets Newsletter) and AskWoody Plus Alerts, emails when there are important breaking developments.
Get Plus!
Welcome to our unique respite from the madness.
It's easy to post questions about Windows 11, Windows 10, Win8.1, Win7, Surface, Office, or browse through our Forums. Post anonymously or register for greater privileges. Keep it civil, please: Decorous Lounge rules strictly enforced. Questions? Contact Customer Support.
Search Newsletters
Search Forums
View the Forum
Search for Topics
Recent Topics
-
Privacy and the Real ID
by
Susan Bradley
50 minutes ago -
MS-DEFCON 2: Deferring that upgrade
by
Susan Bradley
9 hours, 1 minute ago -
Cant log on to oldergeeks.Com
by
WSJonharnew
10 hours, 50 minutes ago -
Upgrading from Win 10
by
WSjcgc50
4 hours, 9 minutes ago -
USB webcam / microphone missing after KB5050009 update
by
WSlloydkuhnle
2 hours, 54 minutes ago -
TeleMessage, a modified Signal clone used by US government has been hacked
by
Alex5723
23 hours, 28 minutes ago -
The story of Windows Longhorn
by
Cybertooth
11 hours, 12 minutes ago -
Red x next to folder on OneDrive iPadOS
by
dmt_3904
1 day, 1 hour ago -
Are manuals extinct?
by
Susan Bradley
5 hours, 26 minutes ago -
Canonical ditching Sudo for Rust Sudo -rs starting with Ubuntu
by
Alex5723
1 day, 10 hours ago -
Network Issue
by
Casey H
21 hours, 39 minutes ago -
Fedora Linux is now an official WSL distro
by
Alex5723
1 day, 22 hours ago -
May 2025 Office non-Security updates
by
PKCano
1 day, 23 hours ago -
Windows 10 filehistory including onedrive folder
by
Steve Bondy
2 days ago -
pages print on restart (Win 11 23H2)
by
cyraxote
1 day, 1 hour ago -
Windows 11 Insider Preview build 26200.5581 released to DEV
by
joep517
2 days, 3 hours ago -
Windows 11 Insider Preview build 26120.3950 (24H2) released to BETA
by
joep517
2 days, 3 hours ago -
Proton to drop prices after ruling against “Apple tax”
by
Cybertooth
2 days, 10 hours ago -
24H2 Installer – don’t see Option for non destructive install
by
JP
1 day, 2 hours ago -
Asking Again here (New User and Fast change only backups)
by
thymej
2 days, 21 hours ago -
How much I spent on the Mac mini
by
Will Fastie
5 hours, 16 minutes ago -
How to get rid of Copilot in Microsoft 365
by
Lance Whitney
1 day ago -
Spring cleanup — 2025
by
Deanna McElveen
3 days, 3 hours ago -
Setting up Windows 11
by
Susan Bradley
1 day, 22 hours ago -
VLC Introduces Cutting-Edge AI Subtitling and Translation Capabilities
by
Alex5723
2 days, 23 hours ago -
Powershell version?
by
CWBillow
3 days ago -
SendTom Toys
by
CWBillow
1 day, 10 hours ago -
Add shortcut to taskbar?
by
CWBillow
3 days, 3 hours ago -
Sycophancy in GPT-4o: What happened
by
Alex5723
3 days, 20 hours ago -
How can I install Skype on Windows 7?
by
Help
3 days, 19 hours ago
Recent blog posts
Key Links
Want to Advertise in the free newsletter? How about a gift subscription in honor of a birthday? Send an email to sb@askwoody.com to ask how.
Mastodon profile for DefConPatch
Mastodon profile for AskWoody
Home • About • FAQ • Posts & Privacy • Forums • My Account
Register • Free Newsletter • Plus Membership • Gift Certificates • MS-DEFCON Alerts
Copyright ©2004-2025 by AskWoody Tech LLC. All Rights Reserved.