MS Access 2016 vba: Empty value passed from form field (text box) - vba

I'm having a strange situation:
I have a simple form with 2 text boxes.
The second one has the vba code triggered after being updated.
For example: typing value to the first field, ENTER, typing value into the second field, ENTER and the code starts.
The code, initially, takes the values from the text boxes and assign them to the string variables (pre declared as strings), like:
test1 = Me.frmSSN.Value
The problem is, the test1 variable seems to be empty after the line above.
It seems to happen only when I type, for example this string:
073QB8KJ2D00A4X
It works fine, when entering CNB0K2W5JK
The tool is a simple serial number comparison.
Just for test, I've entered this line into the code:
aaa="073QB8KJ2D00A4X"
When running in the step-by-step mode and hovering mouse over the "aaa" I'm getting: aaa= and then nothing.
Not even single "" like aaa="" or so. Just aaa=
After retrying multiple things - I believe it's about the value I enter:
073QB8KJ2D00A4X
Could be, that for access/vba it's some control string or so?
I'm just dumb now...
Thanks in advance for any help
Marek
p.s. Source fields are plain text boxes. And here's the code:
Dim user As String
Dim 1stSN As String
Dim 2ndSN As String
1stSN = Me.frmSSN.Value
2ndSN = Me.frmHPSN.Value
Then the values are being used as a part of SQL query. The problem is - in this situation - query doesn't work, as the sql string looks like:
"Select * From sbo_SerialSource where SN like " and nothing after "like".
Debug shows the correct value (with serial number), but query fails with "syntax error" message. Seems like there are some strange "control characters" are being created/added.
That's it.
And I have to use the serial numbers as these "strange ones", because that's how they come from the vendor.

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.

Retrieve Column 1 value from VBA ComboBox after using "combobox.value =" to modify selected index value

Hello I am working with VBA and I have run into a strange situation. I am hoping that someone out there has run into the same thing and can give me a little help. In my program, there is a 2 column combo box that has it's value set to a string. The value is set like this:
ComboBox1.Value = "this_string"
Initially this ComboBox has 2 legit columns. I am able to confirm this by using the Immediate Window Later in code the first column of that combo box is checked. For example:
value = ComboBox1.Column(0)
But the code breaks here. I get this error:
Could not get the Column property. Invalid property array index.
After the value assignment. I can no longer get any Column values. Why is this?
Thank you for your help,
Billy
This question should not have a vb6 tag. - Unlike VBA, Vb6 only has single column comboboxes.

MS Access query custom function accepting form text input as value

G'day, everyone.
I've been banging my head against this question the whole day through today, and I haven't managed to find any answers, so I'd appreciate your help.
What I have:
An Access form containing a text field
A query which is the form's data source
A custom function called RegExp defined within a module
RegExp takes two values as input: string (obtained from a table) and pattern (obtained from the form). RegExp returns a boolean value which in turn thins out query results.
The function works perfectly fine and as expected, however, this is only the case when the user fills out the text field. If the field is left blank, no results are returned (and the function's not even getting called if that's the case).
So here's what that particular statement within the query looks like:
... AND (RegExp(tblRole.Description,Trim([Forms]![frmFindRole]![txtRegExp]))<>False) AND ...
(Basically, to sum it up, user types in a value into the text field which gets leading and trailing spaces trimmed off, converted to a regular expression inside a VBA module, and then query results get filtered based on what boolean value the function returns).
There is a number of controls on this form, and they worked prior to me adding that txtRegExp text field. Now the query only returns results if txtRegExp is filled out, and I have no idea why. I've tried adding more checks, but the query's too complicated already, and I haven't succeeded.
If additional code samples are required for an answer to be made, I'll be able to provide them tomorrow.
Thank you in advance.
P.S. Would Nz help? If yes, then how would I go about using it?
Based on the few explanations you gave in comments
Suppose that this is code triggered on the KeyUp event :
Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
Me.Requery
End Sub
Store the default SQL for your form's recordsource somewhere in a local variable. In this example I considered that you stored it in SQLdefault string.
Prior to requery, check if the textbox is empty and if yes change your form's recordsource SQL accordingly:
private SQLdefault as string
Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
Dim SQL As String
If Nz(txtRegExp, "") = "" Then
SQL = SQLdefault
SQL = Replace(SQL, "AND (RegExp(tblRole.Description,Trim([Forms]![frmFindRole]![txtRegExp]))<>False)", "")
Me.RecordSource = SQL ' Normally this is enought to requery, if not uncomment below
'Me.Requery
Else
Me.RecordSource = SQLdefault ' Normally this is enought to requery, if not uncomment below
' Me.Requery
End If
End Sub
In this example I just remove the SQL part containning :
AND (RegExp(tblRole.Description,Trim([Forms]![frmFindRole]![txtRegExp]))<>False)
Replace it by something else if that's not correct.
That's obviously not the most elegant solution but it's difficult to provide with the best solution with what you've shown.
I've managed to make it work by modifying my initial query to include a check for the value of txtRegExp.
I am still not entirely sure why it failed with a blank txtRegExp value. I have a feeling the RegExp function somehow didn't fire when provided with NULL as the second parameter.
I am very grateful to Thomas G for all the help he's provided.

Handling ⅝ (five eights) Vulgar fraction as part of a string in VBA

As part of an access application, i retrieve data from sql server. I have a string field that contains ⅝ in one of the rows, and when i attempt to insert that value into an MsAccess recordset, i get an error
Multiple-step operation generated errors. Check each status value. Here is my code
sFieldValue = getValue() ' when i add a watch, the '⅝' is replaced by a ? e.g. "The result is ⅝" will be shown as "The result is ?"
Rs(sFieldName) = sFieldValue ' error is thrown
I then attempted to hard code the value in VBA
sFieldValue ="⅝"
And the moment i type '⅝' it automatically changes to a question mark
sFieldValue ="?"
I would like to know how i can support characters such as "⅝". The other fractions work just fine, e.g. '½'. I do not want to do any calculations, the fractions are part of a string that comes from a SQL Server, and the problem is, i get a runtime error when i try to add a string value that contains a fraction to a recordset in access.
from this page, it shows that some fractions are supported in utf-8
The problem was that the field type of Rs(sFieldName) was adVarChar. So to fix the problem, i used a adVariant field type in my recordset, and it now accepts the ⅝ vulgar character.
I am creating the recordset on the fly.
Edit: adVarWChar is more appropriate, see comment below

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.