DoCmd.Open Report Where Clause Syntax Issues With Multiple Criteria And Strings - vba

New Member Here - Happy to Be With You!
I'm Hoping you can help me with what seems to me to be a syntax issue. I have a report with multiple subreports, all of which are based upon queries. The queries have criteria to prompt the user to [Enter SampleID]. When I run the report, it works correctly but is cumbersome because I am prompted for each criteria individually so I wanted to create a form with a button and an input field for the user to enter a SampleID. Then the code would pull that SampleID and use it to "answer" the criteria prompts. Clearly, what I have done so far is incorrect as I receive a run time error 13 type mismatch...I tried to find guidance as to how to proper syntax for strings, but those edits don't seem to work :(
Here's the start of the current code for your review and insights - it continues on but the syntax is the same throughout. Note that SampleID is a short text string.
DoCmd.OpenReport "DEV_GenRpt_Comp_Info", , , "Samples.SampleID=" & Me.SampleID And "ReportDemos_TestOrderAndSampleReportInfo.Samples.SampleID=" & Me.SampleID And "200_8_Query.SampleID=" & Me.SampleID And "300_Query.SampleID=" & Me.SampleID
Most appreciated!

Related

Replacing a DECLARE in an SQL command with a cell value [duplicate]

I "linked" Excel to Sql and it worked fine - I wrote some SQL script and it worked great. All I want to do is to pass parameter to query. Like every time I make refresh I want to be able to pass parameter (filter condition) to Sql Query.
In "Connection Properties" Parameters button is disabled. So I can't make parameter query.
Can Anyone help me?
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes:
Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous.
If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

MS Access: Query to list number of files in a series of folders

I have folders labeled by their keyfield, so 1, 2, ... 999, 1000. located in currentproject.path\RecordFiles\KeyFieldHere so like currentproject.path\RecordFiles\917.
I want to run a query that will count how many files are in each folder. I know this can be done with the DIR function through visual basic, but I can't seem to run it through a SQL query.
I've tried using this function in a SQL equation, so Expr1: [FlrFileCount("Y:\Education\Databases\RecordFiles\")] as one of the fields just to see if it can work, but it prompts me for a value and then returns nothing.
EDIT: I tried an approach using the FlrFileCount function in a continuous form, and it does work, BUT... I get an error after every single line. I have a field in a continuous form of =FlrFileCount([currentproject].[path] & "\recordfiles\" & [ID]), but when I run the form I get an error "Error 76, Error source: FlrFileCount, Error description: Path not found." Which is crazy because IT WORKS, it properly lists the number of files in the folder for each record.
I just need to get this functionality over into a SQL query so I can pull that data for mail merges.
I currently have something similar in a form. The form has an onload property to run a module (Link here) to create a list of all the files in the relevant folder to that record, and then I have another field that just counts the number of entries in the list. However a list can't be a value in a SQL query, so I don't think that code will help.
Thanks to Tim Williams, the answer was to put
=FlrFileCount(Currentproject.Path & "\recordfiles\" & [ID])
It seems the [currentproject].[path] part was where the error was. What's confusing is that in other places, MS Access adds the extra [] around currentproject and path, and I don't know why.
Thank you so much for your help! Now to the tricky part: Implementing a proper naming scheme by program ID across a sharepoint so that the relevant folder can be opened consistently even when program names change.

MS ACCESS SQL query Excel sheet

SELECT f.card_serial_num, count(1) AS CardRxCnt
FROM [Excel 8.0;HDR=Yes;Database=C:\Users\Mike\Desktop\er.xls].[er$] AS f
WHERE f.location_name not like 'PREPACK'
and f.card_type not in ('PRN','sequential')
and (f.card_due_date = #9/15/2014# or f.card_due_date = #10/1/2014#)
GROUP BY f.card_serial_num
HAVING CardRxCnt >2
I have a problem with HAVING CardRxCnt >2. If I take out, I get my query returned.
But if I have it in, it somehow prompts for an input and so when I just put 1 it
returns nothing. Actually without CardRxCnt, sometimes the query prompts
for an input at which I enter 1 and the query executes. Yet other times it would just go through. So my question is two part:
what could be causing this random behavior of "asking"? I know to prompt for a user input, I have to surround a value with []. Could it be the Excel part?
CardRxCnt (in SELECT and HAVING): I don't see what's wrong with it but when I add this, query does not work.
Please help. And I can't do VBA/macro here so if you're gonna say why don't you query with VBA it's not a solution for me.

How do I edit an Access report on the fly?

This seems like it would be pretty simple, but I’ve been googling my brains out for the last two weeks and I can’t find the answer. I'm using Access 2010...
I have a form with a button that the user clicks to get a report, that button pops-up a form that ask for the date of the requested report and then the report open with the correct info. The problem is I need to manipulate the data before it is displayed. Some of it I’ve done directly through the SQL statement and some through the Control Source of the text boxes on the report. But some of the data is a little more complicated… I need to extract certain text from a “remarks” field (memo) and I need to concatenate a few fields together separated by a comma, some of which may be blank. I know I can use the “+” to do that as in “lastName & (“,” + firstName) which will eliminate the unwanted trailing comma… but what if “lastName” is blank… I will be left with an unwanted preceding comma???
How do I loop through the data as it is being “written” to the report so as to edit it “on-the-fly”? I don’t want the user to edit the data because I want to get the exact same results every time.
This an answer to the first question (but what if “lastName” is blank):
lastName & IIf(Len(Lastname) > 0, ",", "") & firstName

how to pass parameters to query in SQL (Excel)

I "linked" Excel to Sql and it worked fine - I wrote some SQL script and it worked great. All I want to do is to pass parameter to query. Like every time I make refresh I want to be able to pass parameter (filter condition) to Sql Query.
In "Connection Properties" Parameters button is disabled. So I can't make parameter query.
Can Anyone help me?
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes:
Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous.
If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.