DAO method in MS Access - ms-access

I am unable to get the count of records by openining Ms Access Query, I use the following code.
Private Sub CmdGetData_Click()
Dim WRK As Workspace
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim StrSql As String
Set WRK = DBEngine.Workspaces(0)
Set db = CurrentDb
StrSql = "select * from [QrySalePatti]"
Set rs = db.OpenRecordset(StrSql, dbOpenDynaset)
Do While (Not rs.EOF)
rs.MoveFirst
rs.MoveLast
MsgBox rs.RecordCount
Loop
exitRoutine:
If Not (db Is Nothing) Then
db.Close
Set db = Nothing
End If
Set WRK = Nothing
End Sub

You should not need a Do While loop to get the RecordCount.
Set rs = db.OpenRecordset(StrSql, dbOpenDynaset)
With rs
If Not (.BOF And .EOF) Then
.MoveLast
End If
MsgBox .RecordCount
End With
However if your goal is only to count the rows from QrySalePatti, you could use a SELECT Count(*) query and read the value returned from that.
StrSql = "SELECT Count(*) AS row_count FROM [QrySalePatti]"
Set rs = db.OpenRecordset(StrSql)
MsgBox rs!row_count
Or you could use a DCount expression.
MsgBox DCount("*", "QrySalePatti")

Related

Error 3061 Too few parameters 1 expected

The below is my code. A simple loop to go through records in a query (qryMasterImageFolders) and then call the sub fs.listImages...
However, I keep receiving the 3061 error and the below line is highlighted:
Set rst = qdf.OpenRecordset()
The query does contain records and I have checked the spelling - what am I missing?
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("qryMasterImageFolders")
Set rst = qdf.OpenRecordset()
With rst
Do Until .EOF
fs.listImages DLookup("ImageFolder", "qryMasterImageFolders")
.MoveNext
Loop
End With
rst.Close
Set rst = Nothing
Set qdf = Nothing
Set db = Nothing
I have changed my code and it is now working:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT ImageFolder FROM tmpImagePaths")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
fs.listImages DLookup("ImageFolder", "qryMasterImageFolders")
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
What you should have done:
Set rs = db.OpenRecordset("qryMasterImageFolders")

How to query the database from the VBA console?

Any way I can run a select query within the immediate console of VBA Access 2010 (VBA 7.0)?
This worked for me with a query that return integers:
Public Sub runQuery(ByVal query As String)
Dim DB As DAO.Database: Set DB = CurrentDb()
Dim rst As DAO.Recordset: Set rst = DB.OpenRecordset(query)
Do While Not rst.EOF
Dim rowStr As String: rowStr = ""
Dim fld As Field
For Each fld In rst.Fields
rowStr = rowStr & fld & " "
Next fld
Debug.Print (rowStr)
rst.MoveNext
Loop
End Sub
Then call it from the immediate window:
runQuery "SELECT Foo, Bar FROM MyTable WHERE Foo < 42"

Recordset BOF/EOF cannot handle Nulls

I have a form and want to display a message when there are no records. The SQL in the following code displays no records (Null) (as it should at present). The function does not work as I wish. It neither returns a number nor displays the message. If I put the function in a form that does have records, it counts them accurately.
Public Function NumRecs() As Integer
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT tblClient.ClientName, tblInvoices.SentToPayer, [Adjustment]+[MyFee]+[DBSFee] AS TotFees, tblClient.ClientID, tblDisclosure.ApplicantForenames, tblDisclosure.AppEmail " & _
"FROM ((tblInvoiceDetails INNER JOIN tblDisclosure ON tblInvoiceDetails.DiscLookup = tblDisclosure.ID) INNER JOIN tblInvoices ON tblInvoiceDetails.InvoiceLookup = tblInvoices.ID) INNER JOIN ((tblOfficerDetails INNER JOIN tblOfficers ON tblOfficerDetails.OfficerLookup = tblOfficers.ID) INNER JOIN tblClient ON tblOfficerDetails.ClientLookup = tblClient.ClientID) ON tblInvoices.AppLookup = tblClient.ClientID " & _
"WHERE (((tblInvoices.DatePaid) Is Null)) ")
If Not rs.BOF And Not rs.EOF Then
NumRecs = Me.Recordset.RecordCount
Else
DisplayMessage ("No records.")
NumRecs = 0
End If
rs.Close
Set rs = Nothing
End Function
"I have a form and want to display a message when there are no records."
You can accomplish that task without opening another DAO.Recordset. Just use RecordsetClone, which already exists.
Private Sub Form_Load()
Dim lngRowCount As Long
lngRowCount = 0
With Me.RecordsetClone
If Not (.BOF And .EOF) Then
.MoveLast
lngRowCount = .RecordCount
End If
End With
MsgBox lngRowCount & " records"
End Sub
Whenever I need a record count in DAO I always MoveLast and then MoveFirst however
Dim db as DAO.Database
Dim rst as DAO.Recordset
Dim strSQL as string
strSQL = "" ' your query here
Set db=CurrentDB()
Set rst=db.OpenRecordset(stSQL,dbOpenDynaSet)
With rst
If NOT (.EOF and .BOF) Then ' There are records to be had
Dim iRecCount as Integer
.MoveLast: .MoveFirst
' DAO typically requires the all records before the count
' count is correct
iRecCount = .RecordCount
Else ' There are NOT records to be had
' ADD YOUR MESSAGE HERE FOR NO RECORDS.
End If
.Close
End with
Set rst=nothing
Set db=nothing
Optionally I build up my Queries external to VBA and add parameters. This why I know my query is producing the results I expect. Then you can reference your query as an object of QueryDefs of CurrentDB() object. Then address you parameters as a property of QueryDef.
The following is a great read from Allen Browne on Recordsets.
http://allenbrowne.com/ser-29.html
All you really need is:
Public Function NumRecs() As Integer
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
If rs.RecordCount = 0 Then
DisplayMessage ("No records.")
Else
rs.MoveLast
NumRecs = rs.RecordCount
End If
rs.Close
Set rs = Nothing
End Function
In order to get the recordcount with DAO, you need to MoveLast. Also, try changing the 'EOF' check (see below):
Public Function NumRecs() As Integer
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL as String
strSQL = "SELECT tblClient.ClientName, tblInvoices.SentToPayer, [Adjustment]+[MyFee]+[DBSFee] AS TotFees, tblClient.ClientID, tblDisclosure.ApplicantForenames, tblDisclosure.AppEmail " & _
"FROM ((tblInvoiceDetails INNER JOIN tblDisclosure ON tblInvoiceDetails.DiscLookup = tblDisclosure.ID) INNER JOIN tblInvoices ON tblInvoiceDetails.InvoiceLookup = tblInvoices.ID) INNER JOIN ((tblOfficerDetails INNER JOIN tblOfficers ON tblOfficerDetails.OfficerLookup = tblOfficers.ID) INNER JOIN tblClient ON tblOfficerDetails.ClientLookup = tblClient.ClientID) ON tblInvoices.AppLookup = tblClient.ClientID " & _
"WHERE (((tblInvoices.DatePaid) Is Null))"
Set dbs = CurrentDB
Set rs = dbs.OpenRecordset(strSQL)
If Not rs.EOF Then
rs.MoveLast ' ADD THIS LINE
NumRecs = rs.RecordCount
Else
DisplayMessage ("No records.")
NumRecs = 0
End If
rs.Close
Set rs = Nothing
dbs.Close
Set dbs = Nothing
End Function`

Ms Access 2007 record set not auto filling into textbox

I have a module with a procedure inside that looks like this:
Public Sub OpenRecordset()
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("QOff2")
qdf.Parameters(0).Value = [Forms]![Form]![Text10]
Dim db As Database
Dim rs As Recordset
Dim StrBusinesses As String
Set rs = qdf.OpenRecordset
If rs.EOF And rs.BOF Then
MsgBox ("No businesses exist for this Customer")
Exit Sub
Else
rs.MoveFirst
End If
StrBusinesses = ""
Do While Not rs.EOF
StrBusinesses = StrBusinesses & rs!Fnam & ", "
rs.MoveNext
Loop
rs.Close
StrBusinesses = Left(StrBusinesses, Len(StrBusinesses) - 2)
Forms!Form.Badge = StrBusinesses
Set rs = Nothing
End Sub
I am trying to get this module to input the query results into a textbox (forms!form.badge), but I can't seem to get it to do it like my 5 other dlookup functions. When I open up the module and push the green play button, it shows up on the correct textbox but also shows up on the other records as well. It also doesn't show up automatically, nor does it update as you enter in the parameters. Isn't a module supposed to help autofil numerous variables into a text box in place of dlookup for multiple values?
No. If Forms!Form!Badge is an unbound textbox, a value assigned to it will be shown identically for all records.
To individualize, you will need a lookup function which takes the ID or other unique value of the record as parameter(add to textbox):
=LookupBadges([Forms]![Form]![Text10])
Public Function LookupBadges(ByVal Value As Variant) As Variant
Dim db As Database
Dim qd As QueryDef
Dim rs As Recordset
Dim Businesses As String
Set db = CurrentDb
Set qd = db.QueryDefs("QOff2")
qd.Parameters(0).Value = Nz(Value)
Set rs = qd.OpenRecordset
If rs.RecordCount > 0 Then
rs.MoveFirst
Do While Not rs.EOF
Businesses = Businesses & rs!Fnam.Value & ", "
rs.MoveNext
Loop
End If
rs.Close
Businesses = Left(Businesses, Len(Businesses) - 2)
LookupBadges = Businesses
Set rs = Nothing
Set qd = Nothing
Set db = Nothing
End Function

Pass Parameter Query Def

The following code executes a stored procedure pass through query. The paramter is received fromthe form and is passed to the stored procedure. The error says that it is an invalid SQL Statement. I need to know if the code is right and how you connect to the database. The results are returned in a record set. Thanks!
Private Sub Command10_Click()
Dim rs1 As DAO.Recordset
Dim DB As Database
Dim Q As QueryDef
Dim strSQL As String
Set DB = CurrentDb()
Set Q = DB.QueryDefs("Call_SP")
strSQL = "execute dbo.ix_spc_planogram_match " & [Forms]![start]![Selection]![cat_code]
Q.ReturnsRecords = True
Q.SQL = strSQL
Set rs1 = DB.OpenRecordset(strSQL)
Do While Not rs1.EOF
Debug.Print rs1.Fields.Item("POG_DBKEY").Value = "POG_DBKEY"
Debug.Print rs1.Fields.Item("COMP_POG_DBKEY").Value = "COMP_POG_DBKEY"
Debug.Print rs1.Fields.Item("CURR_SKU_CNT").Value = "CURR_SKU_CNT"
Debug.Print rs1.Fields.Item("COMP_SKU_CNT").Value = "COMP_SKU_CNT"
Debug.Print rs1.Fields.Item("SKU_TOTAL").Value = "SKU_TOTAL"
Debug.Print rs1.Fields.Item("MATCHD").Value = "MATCHD"
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
Set rs1 = Nothing
End Sub
CurrentDB is MS Access, but you are executing an SQL Server stored procedure. You need to execute against a connection to the server.
For example:
Dim objcon As New ADODB.Connection
scn = "Provider=sqloledb;Data Source=ServerName;" _
& "Initial Catalog=DBNAME;User Id=USERNAME;Password=Password;"
objcon.Open scn
Set rs = objcon.Execute