CHKarcher
Sep 28 2011, 04:34 PM
I had been using the following to count a query result for a repor wheather or not to display the report
MyCount = DCount("*","QueryName")
What whould I need to to do to replace "QueryName" with an actual statement?
say - "Select * from Mytable where Myfield =34"
or better yet
SQLstr = "Select * from Mytable where Myfield =34"
then
MyCount = DCount("*",SQLstr)
???
TIA
Steve
Doug Steele
Sep 28 2011, 04:42 PM
You'd need something like:
CODE
Dim rs As DAO.Recordset
Dim MyCount = Long
Dim strSQL As String
strSQL = "SELECT Count(*) AS TotalRows FROM MyTable WHERE MyField = 34"
Set rs = CurrentDb.OpenRecordset(strSQL)
MyCount = rs!TotalRows
rs.Close
Set rs = Nothing
If you absolutely must use the original SQL of SELECT * FROM MyTable WHERE MyField = 34, you'd have to do something like:
CODE
Dim rs As DAO.Recordset
Dim MyCount = Long
Dim strSQL As String
strSQL = "SELECT * FROM MyTable WHERE MyField = 34"
Set rs = CurrentDb.OpenRecordset(strSQL)
If rs.EOF = False Then
rs.MoveLast
MyCount = rs.RecordCount
End If
rs.Close
Set rs = Nothing
theDBguy
Sep 28 2011, 04:42 PM
Hi Steve,
What version of Access are you using? I don't think you can use a SQL statement inside a DCount() function. You might have to write your own custom function that will accept SQL statements. What is the purpose of using a SQL statement? If only because the criteria changes, then DCount() function already has a facility for that. The syntax is:
DCount("*", "TableName", "FieldName=Value")
Just my 2 cents...
EDIT: And looks like Doug already wrote that custom function for you. Cheers!
CHKarcher
Sep 28 2011, 04:49 PM
I got this to work too
SQLStr = 'MyField = 34"
QCount = DCount("*", "Mytable", SQLstr)
If QCount = 0 Then
MsgBox "No Records Returned for Report", vbInformation, "No Records"
Else
'Opens Report with Where filter
DoCmd.OpenReport strDoc, acViewPreview, , SQLstr
End If
Thanks
Steve
theDBguy
Sep 28 2011, 04:53 PM
Hi Steve,
Glad to hear you figured it out. Good luck with your project.
PS. For your scenario, another option is to use the Report's NoData event.
Cheers
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please
click here.