Why does my database object show no Recordsets? - ms-access

Why does my database object show no Recordsets? And why does it not show a Connection? The key bit of code is:
Public Sub PrintRecords()
Dim dbCurr As DAO.Database
Set dbCurr = CurrentDb
Dim rsCourses as Recordset
Set rsCourses = CurrentDb.OpenRecordset(“Courses”)
End Sub
Here is my screenshot, where the database has tables (upper left), but the CurrentDB object has a name but no Recordsets (in the locals window below.)
For what it’s worth, this is in Access 2013, following this tutorial to manipulate the database, stopping on the error “Run-time error ‘3078’: The Microsoft Access database engine cannot find the input table or query”. But the problem seems to be deeper than that.

You have typographic quotes in there, use straight ones "".
And use your assigned database object:
Set rsCourses = dbCurr.OpenRecordset("Courses")
And please don't post only screenshots of code, copy & paste the code itself as text.

Related

MS Access delete then append tabledef breaks querydef

Following this question thread, was able to successfully code the change suggested by "changing the sourcetable of a linked table in access 2007 with C#". However, it appears this customer has queries coded with relationships defined at the query level and the delete/append process breaks the relationships. Anyone have any idea how to preserve the relationships? And why is it that the tabledef.Sourcetable can't be updated?
Code snip:
Option Compare Database
Sub test()
Dim tdf As TableDef
Dim db As Database
Set db = CurrentDb
Open "out.txt" For Output As #1
For Each tdf In db.TableDefs
If tdf.Connect <> vbNullString Then
Print #1, tdf.Name; " -- "; tdf.SourceTableName; " -- "; tdf.Connect
Select Case tdf.SourceTableName
Case "CTITLU.txt"
'tdf.SourceTableName = "dbo.GRANTSADJS"
'tdf.Connect = "ODBC;DRIVER=SQL Server;SERVER=DCFTDBCL01-L01\EDS_DEV;DATABASE=GRANTSDB2;UID=grants_reader;PWD=xxxxx;TABLE=DBO.GRANTSTABL"
tdf.RefreshLink
End Select
End If
Next
End Sub
When I run this with just the tdf.connect syntax uncommented, it errors on the tdf.refreshlink call with "Run-time error '3011': The Microsoft Access database engine could not find the object 'objectname'..." I'm trying to update a text linked table to the equivalent SQL Server based linked table. The objectname does have spaces and hyphens in it, but it is correctly showing the name in the error message. For whatever reason, the previous developer shipped dumps of the tables to a file system instead of linking the tables directly. This is a small DB with very light transactional activity so there is very little chance this will cause any issues. When the tdf.SourceTableName is uncommented, throws the "Run-time error '3268': Cannot set this property once the object is part of a collection."
I followed other threads indicating this issue (noted above), and was successful using the tdf.delete / tdf.append calls to duplicate the tabledef with new source tablename and connection info. However, the dependent query's relationship definitions have disappeared and the query is unusable without redefining all of the links.
C Perkins, thanks, that was it. There was a slight difference in the table definition such that when using delete/append, it 'broke' the relationships (yes joins) in the related query. Using a DB view to fix that, it worked just fine. However it still 'moves' the query from its former place as being related to the original table object. Our customers will at least have their current data and not a weekly snapshot. Thanks again.

How do I create copies of CurrentDb using VBA

I need to create copies of the CurrentDB using VBA (approx. 12 copies). The copies need to be clones of the master database containing all the same forms, queries, etc. except only a limited dataset.
DoCmd.CopyDatabaseFile seems to be made for this, but only works if you are using it to copy the DB to an MS SQL Server. As MS states on their website:
Copies the database connected to the current project to a Microsoft
SQL Server database file for export.
docmd.TransferDatabase only exports the data itself, but not the structure, forms, etc.
Code I have found on the web and adapted doesn't work and throws an error on the .CopyFile line saying:
Run-time error 52: Bad file name or number
This is the code
Sub CopyDB()
Dim external_db As Object
Dim sDBsource As String
Dim sDBdest As String
sDBsource = "\\group\bsc\groups\L\BDTP\Compliance\ComplianceData\Compliance Group Reporting.accdb"
sDBdest = "\\group\bsc\groups\L\BDTP\Compliance\ComplianceData\Compliance Group Reporting_2.accdb"""
Set external_db = CreateObject("Scripting.FileSystemObject")
external_db.CopyFile sDBsource, sDBdest, True
Set external_db = Nothing
End Sub
How can I fix the above line? Alternatively is there a direct command in Access to create a copy? The "create backup" function would be tailor made for this, but I can not find it in VBA.
Looks like you have an extra quote in sDBdest accdb"""
And for database copy you can also use
FileCopy sDBsource, sDBdest
Instead of Scripting object

Microsoft VBScript compilation error: Expected end of statement

I am trying to insert some records into MS Access Table with the help of below VB Script. But when am trying to execute it, it's throwing Compilation error: Expected end of statement. Could someone please help me figure out where am I going wrong.
Private Sub Form_Click()
Dim dbs As DAO.Database
Dim DbFullNAme As String
DbFullName = "D:\G\Diamond\FINAL MS-Access\MS-Access project.accdb"
Set dbs = OpenDatabase(DbFullName)
dbs.Execute "INSERT INTO [2014_Status] ( Prompt, Project_Name, STATUS,Release_Name )SELECT RoadMap.SPRF_CC, RoadMap.SPRF_Name, RoadMap.Project_Phase,RoadMap.Release_Name FROM RoadMap WHERE (((Exists (select 1 FROM [2014_Status] where RoadMap.SPRF_CC = [2014_Status].[Prompt]))=False));"
dbs.Close
End Sub
VBScript (as opposed to VBA or other dialects) does not support typed Dims. So
Dim dbs As DAO.Database
Dim DbFullNAme As String
need to be
Dim dbs
Dim DbFullNAme
VBscript has no native OpenDatabase() function. You need to use ADO to connect to your Access 'database'. First create a connection
Set dbs = CreateObject("ADODB.Connection")
Then determine the connection string and
dbs.Open cs
The rest of your code should work.
Update wrt comment:
The error message:
D:\G\Diamond\FINAL MS-Access\query1.vbs(2, 9) Microsoft VBScript compilation error: Expected end of statement
prooves that the OT tried to write a VBScript (the addition of the misleading vba/access tags is (C) Pankaj Jaju).
So lets break down the real reason why this code doesn't work.
You copied and pasted Visual Basic for Applications(VBA) into a .VBS(Visual Basic Script) file and expected it to work, I assume.
The problem with this is that VBA and VBScript are slightly different languages. Review the info section for both tags on stackoverflow when you get the opportunity.
For now lets just patch your code and maintain your DAO object so you don't have to reconstruct your Database usage with ADODB.
ExecuteInsert
Sub ExecuteInsert()
Dim dbs, DbFullName, acc
Set acc = createobject("Access.Application")
DbFullName = "D:\G\Diamond\FINAL MS-Access\MS-Access project.accdb"
Set dbs = acc.DBEngine.OpenDatabase(DbFullName, False, False)
dbs.Execute "INSERT INTO [2014_Status] ( Prompt, Project_Name, STATUS,Release_Name )SELECT RoadMap.SPRF_CC, RoadMap.SPRF_Name, RoadMap.Project_Phase,RoadMap.Release_Name FROM RoadMap WHERE (((Exists (select 1 FROM [2014_Status] where RoadMap.SPRF_CC = [2014_Status].[Prompt]))=False));"
dbs.Close
msgbox "done"
End Sub
Changes made.
Blocked your dim'd variables and removed As *** statements for vbscript compatibility
Set an access object so you could maintain the remainder of your code.
Added the acc.DBEngine. before OpenDatabase with additional parameters.
Renamed your Sub from Form_Click to ExecuteInsert, then placed ExecuteInsert at the top of the code so that the vbscript activates the sub. If you just place a sub in a vbscript file, it will not necessarily run, you have to activate it directly.
This code is tested and functions. Best of luck to you.
Adding to Ekkehard.Horner
http://www.csidata.com/custserv/onlinehelp/vbsdocs/vbs6.htm
VBScript has only one data type called a Variant. A Variant is a
special kind of data type that can contain different kinds of
information, depending on how it's used. Because Variant is the only
data type in VBScript, it's also the data type returned by all
functions in VBScript.

Help Debugging this Code to Convert for .adp file type

I had a form with some VB code that was using Access 2003. Recently we wanted to use the same form as a small front end interface for another database that has a SQL Server backend. However, the file type for this project in Access is .adp and not all of the vb code is working properly. If you could help me fix the bugs in this code:
Private Sub SurveyNameCombo_AfterUpdate()
Dim db_CFC As DAO.Database
Set db_CFC = CurrentDb
Dim rst As DAO.Recordset, query As String, count As Integer
query = "SELECT DISTINCT SurveyID FROM tbl_SurveyMeta WHERE SurveyName = " & Chr(34) & Me.SurveyNameCombo.Value & Chr(34)
Set rst = db_CFC.OpenRecordset(query)
count = rst.RecordCount
If count > 1 Then
Me.SurveyIDCombo.RowSource = query
Else
rst.MoveFirst
Me.SurveyIDCombo.Value = rst.Fields(0).Value
Call SurveyIDCombo_AfterUpdate
End If
End Sub
It is throwing errors in the for the DAO.Database and DAO.Recordset.
Thank you for your help!
The error message "User-defined type not defined" on a line such as this ...
Dim db_CFC As DAO.Database
... means your application doesn't include a reference to the Microsoft DAO Object Library.
Open a code module, then check from the main menu in the VBE editor: Tools->References
Ordinarily the cure would be to place a check mark in the box next to Microsoft DAO Object Library, then click OK. However, your application is an ADP, and I don't know whether DAO can even be used in ADP. You can try. :-)
Sorry I can't tell you more. I quit using ADP a few years ago. Instead I use the MDB format with ODBC links to SQL Server database objects. Perhaps you could consider the same approach if you're unable to get the ADP version working as you need.

Why can't I re-link a table with vba using the CurrentDB() method directly?

Could anyone explain why the first code example works but the second doesn't?
This re-link code DOES work:
Dim db As Database
Dim sNewLinkAddress As String
sNewLinkAddress = "C:\temp\backend.accdb"
Set db = CurrentDb
db.TableDefs("table1").Connect = ";Database=" & sNewLinkAddress
db.TableDefs("table1").RefreshLink
This re-link code DOES NOT work, but no error messages are given:
Dim sNewLinkAddress As String
sNewLinkAddress = "C:\temp\backend.accdb"
CurrentDb().TableDefs("table1").Connect = ";Database=" & sNewLinkAddress
CurrentDb().TableDefs("table1").RefreshLink
What concerns me is that there is a fundamental difference that I'm unaware of between using the Database object directly returned by CurrentDB() and using a variable 'db' that is set to the Database object returned by CurrentDB(). To my mind both ways should be identical, but obviously I'm wrong!
In the past I have used CurrentDB() directly for various things such as opening a recordset with no problem. There seems to be a specific issue with re-linking tables. Any ideas to what's going on here?
I'm using access 2007, but the same issue applies to 2003 also.
Every time you call CurrentDb() it returns a new instance of the database object.
To illustrate what I mean I'll use letters to represent the database instance (the letters are arbitrary and used only to make it easier to follow the logic).
So in your first example you are using assigning the return value of CurrentDb to a database object db. Then each time you call db you are referring to the same database object instance:
Set db<A> = CurrentDb
db<A>.TableDefs("table1").Connect = ";Database=" & sNewLinkAddress
db<A>.TableDefs("table1").RefreshLink
In your second example you make multiple calls to the CurrentDb function and each call returns a different database object instance:
CurrentDb()<B>.TableDefs("table1").Connect = ";Database=" & sNewLinkAddress
CurrentDb()<C>.TableDefs("table1").RefreshLink
The upshot here is that when you call RefreshLink on the second line you are doing it against a brand new instance of the database object; ie, one whose "table1" Connect property has not been changed.