How to add double quotes in VBA strings
VBA strings are enclosed in double-quotes. For example:
Sometimes, you need to present or store text that needs to be enclosed in double-quotes.
However, VBA produces an error if you try doing that. For example,
This will generate an error.
So, how do you include double quotes in your strings in VBA?
The answer is using Chr() function with 34 code.
Code 34 is the ASCII value for ” (Double Quotes).
An example of using Str(34) in a message box
As you run this code, a message box with a text message will display with double-quoted text.
Sub chr34_ex() MsgBox "This is a " & Chr(34) & "VBA" & Chr(34) & " Tutorial" End Sub
Result:
How is it done? We concatenated Chr(34) to the string twice – both sides of the text “VBA”.
Using double quotes in a string variable example
Similarly, you may enclose some text in the double quotes when using VBA string variables.
The following example shows how:
Sub chr34_ex() Dim Str As String Str = Chr(34) & " As I would not be a slave, so I would not be a master. This expresses my idea of democracy. " & Chr(34) & Chr(10) & Chr(10) & "Abraham Lincoln" MsgBox Str End Sub
Result:
Writing text to Excel cell with double quotes
The following example writes double-quoted text to an Excel cell:
Sub chr34_ex() Dim Str As String Str = Chr(34) & " The ballot is stronger than the bullet." & Chr(34) & Chr(10) & Chr(10) & "Abraham Lincoln" Range("A2") = Str End Sub
Result: