I need to build a large string (json) in VBA with quotes in it.
I tried this approach:
Dim payload As String
payload = ""
payload = payload & CHR(34) & {"timeframeId":13,"startDate":"2021-05-31 00:00:00.000","endDate":"2021-05-31 00:00:00.000","peopleList":[{"id":123}], & CHR(34)
...more lines building string
But the Excel IDE for VBA complains of a syntax error - presumeably to do with the quoted strings?
Do I need to add CHR(34) before the opening and after closing " of each?
Al Grant!
Chr(39) or " double quote char is the text qualifier to VBA, so you need to do an ajustment to use in the strings.
I presume you have this value anywhere in the worksheet.
So the common way to do this is set the range and use replace to another char, and after all back to chr(39).
If you what to input in hardcode, you will need to concatenate chr(39) with everytime a doublequote appears, or use ""
But the easiest way is to replace find and replace (CTRL+H) to another char, and continue to develop like you was doing
Dim payload As String
payload = payload & Chr(34) & Replace("{'timeframeId':13,'startDate':'2021-05-31 00:00:00.000','endDate':'2021-05-31 00:00:00.000','peopleList':[{'id':123}],", Chr(39), Chr(34)) & Chr(34)
Debug.Print payload
Result:
"{"timeframeId":13,"startDate":"2021-05-31 00:00:00.000","endDate":"2021-05-31 00:00:00.000","peopleList":[{"id":123}],"
Related
I'm trying to run this code:
Set Lrs = db.OpenRecordset("Select [LastName]" & _
"From ['Chromebook Registration Form]" & _
"Where [InventoryNumber] = dbInventoryNumber ")
Where "dbInventoryNumber" is a double variable. The field [InventoryNumber] takes a double, but when I run this I get a 3061 Run-time error. Too few arguments. Expected 1.
I know how to pass string variables as parameters, but how do I do it for doubles?
Thanks!
Although the [ ]s will allow the SQL to evaluate, should include space at end of each continued line so SQL string doesn't run together when compiled. Pass double variable same way as string except don't use apostrophe delimiters. (Date/time field parameters use # delimiter.) Don't put variables within quote marks, concatenate them. Remove apostrophe in front of source (assuming this is not really in source name - advise no spaces nor punctuation/special characters in naming convention). Source name that includes word "Form" sounds like name of a form. Source must be a table or query.
Set Lrs = db.OpenRecordset("Select [LastName] " & _
"From [Chromebook Registration Form] " & _
"Where [InventoryNumber] = " & dbInventoryNumber)
I want to insert an if statement in a cell through vba which includes double quotes.
Here is my code:
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!B1=0,"",Sheet1!B1)"
Due to double quotes I am having issues with inserting the string. How do I handle double quotes?
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.
Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.
Sub RepairFormula()
Dim FormulaString As String
FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString
This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.
All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard",
In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.
I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
It is originally posted on Chandoo.org forums' Vault Section.
In case the comment by gicalle ever dies:
I prefer creating a global variable:
Public Const vbDoubleQuote As String = """" 'represents 1 double quote (")
Public Const vbSingleQuote As String = "'" 'represents 1 single quote (')
and using it like so:
Shell "explorer.exe " & vbDoubleQuote & sPath & vbDoubleQuote, vbNormalFocus
I have a form-field (textarea) in my application, which may contain double-quotes (""). For a JSON-String, I wrote a small "setup", which is send afterwards. I encountered the problem, that if a user uses the double-quotes, my setup breaks.
This is how it looks like so far:
dim payload
payload = payload & "{""short_description"":""" & Replace(Replace(trim(shortDesc),chr(10),""), chr(13), "") & ""","
payload = payload & """description"":""" & Replace(Replace(trim(Description),chr(10),""), chr(13), "") &""","
payload = payload & """u_requester"":"""& sgi &""","
payload = payload & """contact_type"":""Self-service"","
payload = payload & """cmdb_ci"":""" & system &""","
payload = payload & """u_category"":""" & category & """}"
And just to show you where I'm using it:
With http
Call .Open("POST", url, False)
Call .SetRequestHeader("Accept", "application/json")
Call .SetRequestHeader("Content-Type", "application/json")
Call .Send(payload)
End With
The variables used in this method are arguments in the current function.
I thought about escaping double-quotes, but I somehow just end up on sites which suggest I should use chr(34) in a Response.Write, which isn't what I'm looking for.
I also tried to use the Replace-function, similar how I would do this in PHP:
Replace(myvar, '"'; "'")
But as you may figured out, a single-quote starts a comment in classic ASP. How can I get rid off the double-quotes here? It doesn't really matter if I convert " to ' or keep the double-quotes. Any suggestion is appreciated
If you need a visible double quote within a string in asp, you need to double it.
Response.Write("""")
If you want to replace a double quote,
str = Replace(str,"""","")
to display a double quote (or single quote) in a json string, you need to escape it:
str = "this is a ""test""."
strForJson = Replace( str, """", "\""" )
I am using vba-json to parse json and am having trouble preserving spaces in keys. I am new to VBA and didn't see anything in the class to give me the option to preserve spaces in keys.
I am using the class found here
I have:
Function me_()
Dim s, json, i
s = "{'key one':'value one','key two':'value two'}"
Dim lib As New JSONLib
Set json = lib.parse(CStr(s))
For Each i In json
Debug.Print i & "," & json.Item(i)
Next
me_ = "done"
End Function
This preserves the spaces in the values but not the keys:
keyone,value one
keytwo,value two
(jsonlint.com says my json is valid with the spaces in the keys)
It's possible by changing the code, specifically a method parseKey.
Whitespaces (spaces, tabs and various linebreaks) are ignored in keys on line 282:
If InStr(vbCrLf & vbCr & vbLf & vbTab & " ", char) Then
I was just testing my database and I realized that I run into problems wherever a text entry in my database contains a ' character (single quote). My solution for now is that before any .execute operations on a string, I call escape(string, "'", " "'" ").
Summarized example below:
qr = "INSERT INTO tblExample VALUES ( " & "'" & me.testparam & "'" & ");"
qr = Replace(qr, "'", " "'" ")
db.execute qr
'also tried qr = "INSERT INTO tblExample VALUES ( " & "'" & replace(me.testparam,"'"," ") & "'" & ");"
This was what I assumed to be the correct workaround to prevent errors from values such as Tourette's.
There's two problems with this. First of all, it's not working. Second, I have over 50 locations in code throughout my app where I call the statement db.execute qr where qr is a string that could potentially contain a single quote. I need the field in the table to contain the single quote, so I can't just replace it with a space or something similar.
Two part question:
Is there a better solution than going through all of my code calling Replace on every string that is to be executed as a query?
Why is my current implementation failing? - I still get syntax error in query expression even when escaping the single quote to a space.
First examine these 2 lines.
"VALUES ( " & "'" & me.testparam & "'" & ");"
"VALUES ( '" & me.testparam & "');"
Both will produce the exact same string. The difference for me is that my brain comprehends the second version faster.
Now, here is what the comments are telling you to do ... replace each single quote in your source string with two single quotes. I added Debug.Print so you can view the finished string in the Immediate window (go there with Ctrl+g) ... you can then see the actual string rather than trying to imagine what it looks like.
qr = "INSERT INTO tblExample VALUES ( '" & _
Replace(Me.testparam, "'", "''" & "');"
Debug.Print qr
db.Execute qr, dbFailOnError
Since I assumed db is a DAO.Database object variable, I included the dbFailOnError option. You should include an error handler in your code to deal with any problems dbFailOnError exposes.
When you run into trouble with a VBA function in a query, drop to the Immediate window and test your function expression there. This one triggers a compile error, "Expected: list separator or )":
? Replace("Tourette's", "'", " "'" ")
But this one works:
? Replace("Tourette's", "'", "''")
Tourette''s
I mentioned that because it's useful in general, and also because your title starts with "Escaping unwanted characters, mainly single quotes". So if you want to remove/replace other characters, not just single quotes, experiment in the Immediate window until you find a Replace() expression which works. Then use that expression in your query.
For example, if unwanted characters include line breaks ...
MyString = "foo" & vbCrlf & "bar" : ? MyString
foo
bar
? Replace(MyString, Chr(13) & Chr(10), " ")
foo bar
Note: I used Chr(13) & Chr(10) rather than vbCrlf as the find target because the db engine can use the Chr() function but doesn't know about the named constant (vbCrlf).
Your query is failing because you have not said where to insert :
Dim qd As QueryDef
qr = "INSERT INTO tblExample (AText) VALUES ( [avalue] );"
Set qd = CurrentDB.CreateQueryDef("",qr)
qd.Parameters("avalue").Value = me.testparam
qd.Execute dbFailOnError
Another method is to define a quote as constant (Const Quote = """") and use that to build SQL Statements. It is not possible to define a quote as Const Quote = Chr(34) as a constant definition can't be based on a function so one has to use four double quotes in a row. The third quote is what you are saving, the second quote is to excape the third quote and the first and last quote are because the value you are assigning is a string.
You will then be able to build SQL statements such as:
SQL = SELECT * FROM tblSyndromes
WHERE Syndrome = " & Quote & "Tourette's" & Quote & ";"
It will no longer matter that there are single quotes in your data.
I don't use parameters as if I upscale my database to sql server and convert my queries to pass-through queries, I can't use parameters. I rarely upscale but I write all my code with that assumption. Also if your query is not working as expected, how do find out what went wrong. If I have a variable called SQL, then I can always print the SQL statement and run it in a new query to see what it does.