Using a Dlookup in Access VBA when the field has a single quote - vba

I've found a lot on this topic but still can't seem to get it to work. I have the following line of code:
If isNull(DLookup("id", my_table, my_field & "='" & temp_value & "'")) Then
The problem is a value in my_field of my_table is "O'Connell" (with a single quote), and I'm not sure how to get Dlookup to find it. I've tried using:
my_field & "=" & chr(34) & temp_value & chr(34)
And a host of other multi-quote options, but I just can't seem to get it to work. Though I can use VBA to modify the temp_value to include or not include the single quote, since the single quote already exists in the table, I need to make sure it matches. I'm just not sure how to tackle it.

Though the suggestions and answers here do work and resolve many issues with quotes in text, my issue ended up being related to the character I was seeing as a single quote not really being a single quote. For what it's worth, the data I was using was exported from Siebel, and the single quote I was seeing was actually chr(146), where a regular single quote (I say "regular" for lack of a better term) is chr(39).
If having issues with quotes, I found it helpful to examine the chr values of each character in the string. There may be a better way to do this, but this loop should help:
for i=1 to len(a_string)
debug.print mid(a_string,i,1) & " - " & asc(mid(a_string,i,1)
next i
The asc function gives you the chr code for a character, so this loops through the string and shows you each character and its associated chr code in the Immediate window (using debug.print). This also helps in finding other "hidden" (or non-visible) characters that may exist in a string.
Once discovered, I used the replace function to replace chr(146) with two single quotes (two chr(39)s), as suggested by HansUp, and that worked perfectly.

In this example, my_table is the name of my table and my_field is the name of a field in that table.
Dim strCriteria As String
Dim temp_value As String
temp_value = "O'Connell"
' use double instead of single quotes to avoid a '
' problem due to the single quote in the name '
strCriteria = "my_field = """ & temp_value & """"
Debug.Print strCriteria
If IsNull(DLookup("id", "my_table", strCriteria)) Then
MsgBox "no id found"
Else
MsgBox "id found"
End If
If you prefer, you can double up the single quotes within the name. This should work, but make sure you can distinguish between which are double and which are single quotes.
strCriteria = "my_field='" & Replace(temp_value, "'", "''") & "'"

Related

Dsum function not working with Text field

I've tried just about everything i can think of on why i would get this error, but i have had no luck. I wrote a similar code that references that same table with numerical values that works fine, but when searching for text it has problems. The error code says the missing operator lies here: [ExpendetureStore] = 'Lowe's
TotalCostTextBox = DSum("[ExpendetureCost]", "ProjectExpendetures", "[ExpendetureStore] = '" & Me.StoreNameCombo & "'")
Lowe's has an apostrophe in its name. Access query engine is reading that apostrophe as a special character (text delimiter) in the compiled search string. If your data includes apostrophes, one way to deal with is to 'escape' the character - double it in the data with Replace() function. This forces Access to treat the character as normal text.
TotalCostTextBox = DSum("[ExpendetureCost]", "ProjectExpendetures", "[ExpendetureStore] = '" & Replace(Me.StoreNameCombo, "'", "''") & "'")
The same will happen with quote marks and are more challenging to deal with. Note the escaping of quote between quotes.
Replace("somevalue", """", """" & """")
Or may be easier to understand using Chr() function.
Replace("somevalue", Chr(34), Chr(34) & Chr(34))
Side note: Expendeture is a misspelling of Expenditure.

Db Search - Multiple conditions

I am trying to export Documents from a Lotus DB. I have used the Db.search functionality and arrived at below code. However, I want to include 2 conditions/functions - #Contains & #Created together. I am getting Formula error. Any help is much appreciated.
Set GlobalCollection = db.Search("#Created > [01/01/2019]" & " " & "#Contains(" & "App1" & ";" & """Approved""" & ")", Nothing, 0)
The escape symbol for LotusScript is a backslash, \. LotusScript allows you to use more than just double quotes to wrap Strings. You can use curly braces ({...}) or pipes (|...|). This may make it more readable and easier to trubleshoot. There's also no need to have separate strings for each individual piece, which will again minimise risk and help readability. There may have been a mistake with each of those, I'm pretty sure you're missing an ampersand. It's much easier to troubleshoot with fewer strings.
So this should work:
Set GlobalCollection = db.Search({#Created > [01/01/2019] & #Contains(App1;"Approved")}, Nothing, 0)

Invalid Identifier for column showing in schema

I am having trouble querying a column in an Oracle view that shows up when I pull the schema. In fact, it appears as column number 2 when I list it out.
The error indicates ORA-00904 invalid identifier, which from what I have read says the column name I am referencing is incorrect, but I have copied the name directly from Oracle Developer, MSAccess, and the datareader.Schema, all of which appear to have no issues getting to that column.
If I query the column just using a linked table in MSAccess the data also comes right up. All of the examples I have seen referencing a similar issue in which the field is incorrectly typed, which though I acknowledge is still a possibility, seems unlikely in this case given the direct copy from the column list as mentioned.
Other solutions mention putting the name in double quotes, which I am uncertain how to do in VB.NET or if it is even necessary.
Code below:
'Open And Query
oledbCon.ConnectionString = strCon
oledbCon.Open()
oledbCom.Connection = oledbCon
oledbCom.CommandType = CommandType.Text
oledbCom.CommandText = "SELECT AREA_CODE FROM CSITAPPS.DAYSIN_1057"
oledbda.SelectCommand = oledbCom
oledbda.Fill(gdt)
I was able to find a solution working with a co-worker for a couple days. The issue stems from the fact that Oracle Column references are Case Sensitive. Because of this the double quotations were required, which is tricky for VB.net given quotation marks indicate and encapsulate String entries. The solution was to break the string and concatenate chr(34) into it. That in combination with ensuring that the column reference case matched what was in the table it came right up.
"SELECT " & Chr(34) & "Area_Code" & Chr(34) & " FROM CSITAPPS.DAYSIN_1057 ORDER BY " & Chr(34) & "Area_Code" & Chr(34) & " DESC;"

Placing Double Quotes Within a String in VBA

I'm having a hard time understanding how to place a double quote (") within a String in VBA. I know that I can easily do this using the char(34) function. I also understand that another way of doing this is to use 4 double quotes: """". All of this comes from a previous SO post:
How do I put double quotes in a string in vba?
However, my question is.... Why are 4 quotes needed? Do the first two act as the escape, the third is the quote itself, and the fourth is the terminating quote? Or does it work in a different way? I haven't been able to find a concrete answer as to how VBA treats these double quotes.
I've also noticed that if I try adding or removing the number of double quotes within a String, Visual Studio will dynamically add or remove double quotes. For example, I initially had the following String:
data = TGName + """ + iterator.Value + """
...which produces the following within a message box:
However, if I try adjusting the second set of double quotes at the end of the String (+ """) from 3 to 4, Visual Studio automatically adjusts this to 5. There's no way for me to only have 4 quotes at the end. This is the resulting String within a message box:
The Strings within the message boxes aren't the actual output that I'm hoping to have, they're purely for experimental purposes. However, what I've noticed is that there clearly is a requirement for the number of quotes that are allowed within a String in VBA. Does anyone know what that requirement is? Why is the IDE forcefully inserting an additional quote in the second String? Can someone explain the differences between the actual String contents and the formatting quotes within both cases that I've described?
As always, any assistance on this would be greatly appreciated :)
The general rule is as follows.
The first double-quote (DQ) announces the beginning of a string. Afterwards, some DQ announces the end of the string. However, if a DQ is preceded by a DQ, it is "escaped". Escaped means it is a character part of the string, not a delimiter.
Simply put, when you have any even number of consecutive double-quotes inside a string, say 2n, this means there are n escaped double-quotes. When the number is odd, say 2n+1, you have n escaped DQs and a delimiter.
Examples
""" + iterator.Value + """
' delimiter " + iterator.Value + " delimiter
' ^ escaped ^ escaped
""" + iterator.Value + """"
' delimiter " + iterator.Value + "" ' (missing enclosing delimiter)
' ^ escaped ^^ both escaped.
In this latter case the last delimiter is missing, For this reason VS inserted it for you, and you got 5 DQs.
Finally the particular case """" (just 4 DQs), the first and last are delimiters, and inside there's one escaped DQ. This is equivalent to chr(34).
To append iterator value to TGName in quotes, you can do this:
Data = TGName & """" & iterator.Value & """"
or this:
Data = TGName & Chr(34) & iterator.Value & Chr(34)
Note: I replaced + signs with & because that's simply a VBA best practice when concatenating strings.

Access 2007 VBA Query Shows Data in Query Analyzer But Not in VBA Coded Recordset

I have a function I've written that was initially supposed to take a string field and populate an excel spreadsheet with the values. Those values continually came up null. I started tracking it back to the recordset and found that despite the query being valid and running properly through the Access query analyzer the recordset was empty or had missing fields.
To test the problem, I created a sub in which I created a query, opened a recordset, and then paged through the values (outputting them to a messagebox). The most perplexing part of the problem seems to revolve around the "WHERE" clause of the query. If I don't put a "WHERE" clause on the query, the recordset always has data and the values for "DESCRIPTION" are normal.
If I put anything in for the WHERE clause the recordset comes back either totally empty (rs.EOF = true) or the Description field is totally blank where the other fields have values. I want to stress again that if I debug.print the query, I can copy/paste it into the query analyzer and get a valid and returned values that I expect.
I'd sure appreciate some help with this. Thank you!
Private Sub NewTest()
' Dimension Variables
'----------------------------------------------------------
Dim rsNewTest As ADODB.Recordset
Dim sqlNewTest As String
Dim Counter As Integer
' Set variables
'----------------------------------------------------------
Set rsNewTest = New ADODB.Recordset
sqlNewTest = "SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, " & _
"dbo_part.partdescription as Description, dbo_partmtl.qtyper as [Qty Per] " & _
"FROM dbo_partmtl " & _
"LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum " & _
"WHERE dbo_partmtl.mtlpartnum=" & Chr(34) & "3C16470" & Chr(34)
' Open recordset
rsNewTest.Open sqlNewTest, CurrentProject.Connection, adOpenDynamic, adLockOptimistic
Do Until rsNewTest.EOF
For Counter = 0 To rsNewTest.Fields.Count - 1
MsgBox rsNewTest.Fields(Counter).Name
Next
MsgBox rsNewTest.Fields("Description")
rsNewTest.MoveNext
Loop
' close the recordset
rsNewTest.Close
Set rsNewTest = Nothing
End Sub
EDIT: Someone requested that I post the DEBUG.PRINT of the query. Here it is:
SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, dbo_part.partdescription as [Description], dbo_partmtl.qtyper as [Qty Per] FROM dbo_partmtl LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum WHERE dbo_partmtl.mtlpartnum='3C16470'
I have tried double and single quotes using ASCII characters and implicitly.
For example:
"WHERE dbo_partmtl.mtlpartnum='3C16470'"
I even tried your suggestion with chr(39):
"WHERE dbo_partmtl.mtlpartnum=" & Chr(39) & "3C16470" & Chr(39)
Both return a null value for description. However, if I debug.print the query and paste it into the Access query analyzer, it displays just fine. Again (as a side note), if I do a LIKE statement in the WHERE clause, it will give me a completely empty recordset. Something is really wonky here.
Here is an interesting tidbit. The tables are linked to a SQL Server. If I copy the tables (data and structure) locally, the ADO code above worked flawlessly. If I use DAO it works fine. I've tried this code on Windows XP, Access 2003, and various versions of ADO (2.5, 2.6, 2.8). ADO will not work if the tables are linked.
There is some flaw in ADO that causes the issue.
Absolutely I do. Remember, the DEBUG.PRINT query you see runs perfectly in the query analyzer. It returns the following:
Job/Sub Rev Description Qty Per
36511C01 A MAIN ELECTRICAL ENCLOSURE 1
36515C0V A VISION SYSTEM 1
36529C01 A MAIN ELECTRICAL ENCLOSURE 1
However, the same query returns empty values for Description (everything else is the same) when run through the recordset (messagebox errors because of "Null" value).
I tried renaming the "description" field to "testdep", but it's still empty. The only way to make it display data is to remove the WHERE section of the query. I'm starting to believe this is a problem with ADO. Maybe I'll rewriting it with DAO and seeing what results i get.
EDIT: I also tried compacting and repairing a couple of times. No dice.
When using ADO LIKE searches must use % instead of *. I know * works in Access but for some stupid reason ADO won't work unless you use % instead.
I had the same problem and ran accoss this forum while trying to fix it. Replacing *'s with %'s worked for me.
Description is a reserved word - put some [] brackets around it in the SELECT statement
EDIT
Try naming the column something besides Description
Also are you sure you are using the same values in the where clause - because it is a left join so the Description field will be blank if there is no corresponding record in dbo_part
EDIT AGAIN
If you are getting funny results - try a Compact/Repair Database - It might be corrupted
Well, what I feared is the case. It works FINE with DAO but not ADO.
Here is the working code:
Private Sub AltTest()
' Dimension Variables
'----------------------------------------------------------
Dim rsNewTest As DAO.Recordset
Dim dbl As DAO.Database
Dim sqlNewTest As String
Dim Counter As Integer
' Set variables
'----------------------------------------------------------
sqlNewTest = "SELECT dbo_partmtl.partnum as [Job/Sub], dbo_partmtl.revisionnum as Rev, " & _
"dbo_part.partdescription as [TestDep], dbo_partmtl.qtyper as [Qty Per] " & _
"FROM dbo_partmtl " & _
"LEFT JOIN dbo_part ON dbo_partmtl.partnum = dbo_part.partnum " & _
"WHERE dbo_partmtl.mtlpartnum=" & Chr(39) & "3C16470" & Chr(39)
Debug.Print "sqlNewTest: " & sqlNewTest
Set dbl = CurrentDb()
Set rsNewTest = dbl.OpenRecordset(sqlNewTest, dbOpenDynaset)
' rsnewtest.OpenRecordset
Do Until rsNewTest.EOF
For Counter = 0 To rsNewTest.Fields.Count - 1
MsgBox rsNewTest.Fields(Counter).Name
Next
MsgBox rsNewTest.Fields("TestDep")
rsNewTest.MoveNext
Loop
' close the recordset
dbl.Close
Set rsNewTest = Nothing
End Sub
I don't use DAO anywhere in this database and would prefer not to start. Where do we go from here?
I know some time has passed since this thread started, but just in case you're wondering, I have found out some curious about Access 2003 and the bug may have carried over to 2007 (as I can see it has).
I've had a similar problem with a WHERE clause because I needed records from a date field that also contained time, so the entire field contents would look like #6/14/2011 11:50:25 AM# (#'s added for formatting purposes).
Same issue as above, query works fine with the "WHERE ((tblTransactions.TransactionDate) Like '" & QueryDate & "*');" in the query design view, but it won't work in the VBA code using ADO.
So I resorted to using "WHERE ((tblTransactions.TransactionDate) Like '" & QueryDate & " %%:%%:%% %M');" in the VBA code, with ADO and it works just fine. Displays the record I was looking for, the trick is not to use "*" in the Like clause; or at least that was the issue in my case.
I put brackets around the word "Description" in the SELECT statement, but it's behavior remains. It works fine as long as I don't put anything in the WHERE clause. I've found if I put anything in the where clause, the description is blank (despite showing up in the Query analyzer). If I use a LIKE statement in the WHERE clause, the entire recordset is empty but it still works properly in the Query Analyzer.
Ultimately I think it's a problem with running ADO 2.8 on Vista 64
Personally I have always used DAO in Access projects.