When searching for a double quote using Instr, I know that you need to use 4 double quotes for the search string Instr(String,""""), or alternatively, Instr(String, Chr(34)).
What I don't quite understand is why 3 double quotes don't work Instr(String,""")
I have Googled for this, but haven't come across the answer I'm looking for. I realize this is a very basic question, but I can't seem to get my head around it.
The "" is just quoting a " - therefore, """ means "_here comes a double quote - and VBA lacks the closing "!
In other words:
x = "" -> Content of is blank
x = """" -> Content of x is "
x = """ -> VBA cannot compile, as it reads here comes a string (the first ") that contains a double quote ("") - but then does not find the closing "...
Related
I am looking to replace double quotes, ", with backslash escaped double quotes - \".
I read online that you can use double quotes in VBA, if you use two double quotes inside the main double quotes. But, this didn't seem to work for me. For instance I tried the following code:
Function ADDSLASHES(InputString As String)
NewString = Replace(InputString, "\", "\\")
NewString = Replace(NewString, "'", "\'")
NewString = Replace(NewString, """", "\""")
ADDSLASHES = NewString
End Function
When I tested it, this function successfully substituted the single backslash and the single quotes, but not the doule quotes.
I also read that you can use CHR(34), and elsewhere to use CHR(147). But this too didn't work. I tried the following lines:
NewString = Replace(NewString, CHR(34), "\"+CHR(34))
NewString = Replace(NewString, CHR(147), "\"+CHR(147))
But testing it out with a cell that had double quotes did not work. Am I doing something wrong? How might I use double quotes with the Replace() function?
When I entered a"b in a cell, Calc converted it to a right double quote, not a left one. Adding this line made it work:
NewString = Replace(NewString, CHR(148), "\"+CHR(148))
Be aware that x94 (decimal 148) is an extended ASCII encoded character, which is something I would avoid at all costs. It's strongly recommended to only use the first 128 characters as ASCII and to use Unicode for everything else.
The Unicode value for a right double quotation mark is U+201D. Sadly, apparently LibreOffice Basic does not have a native way to work with such values. There is ChrW but that requires the VBA compatibility option. Another method is to call the UNICODE() spreadsheet function from Basic, but that is cumbersome.
My preference: Don't use Basic for anything important. LibreOffice macros can be written in Python instead, which has strong Unicode support.
EDIT:
One thing I forgot to mention yesterday: Select a quotation mark in the formula bar and press Alt+x to find out what it really is. This will convert it to the Unicode value and then back again.
EDIT 2:
That's correct—Alt+X only works in LibreOffice, not AOO. Also for some reason, the extended ASCII code above doesn't seem to work in AOO. Maybe that's not a bad thing. Anyway, here is the Unicode spreadsheet function access approach, and it works for me in both AOO and LO.
fa = createUnoService("com.sun.star.sheet.FunctionAccess")
ch = fa.CallFunction("UNICHAR", Array(CLng("&H201D"))
NewString = Replace(NewString, ch, "\"+ch)
If this doesn't work, then you probably have something else in the cell. To figure out what it is, you could install LibreOffice. Or there are lots of other ways; most often I use GVim text editor. Also I just now googled and found https://www.branah.com/unicode-converter where you can paste some text and see the actual UTF-16 hexadecimal values.
I found answer under the title "Using variables in R1C1 formula construction" that makes my formula work. Can someone explain, the logic as to how a formula is constructed and stored in a cell.
Original:
=IF(ISNUMBER(SEARCH("IAV",RC[-2])),MID(RC[-2],FIND("IAV",RC[-2])+6,11),"")
Working:
sFRM = "=IF(ISNUMBER(SEARCH('IAV',RC[-2])),MID(RC[-2],FIND('IAV',RC[-2])+6,11),'')"
.Range("o2:o" & lr).FormulaR1C1 = Replace(sFRM, Chr(39), Chr(34))
thanks, inadvance
I think you are trying to figure out why there are single quotes in the VBA version, but double quotes in the excel sheet.
In VBA, to create a variable of type string, you put it inside quotation marks.
So the line:
myvar = "help"
causes the variable myvar to be a string with the value of help [without quotes]
But what if you wish to have quotation marks in your string? So you want myvar to actually be equal to
John said "Help"
If you tried to set a variable equal to this, VBA would treat the quotation mark as a symbol exiting the string and would cause an error, such as occurs in the following line:
myvar = "John said "Help""
This would not work, because VBA would see the second quotation mark and think that the string is complete (and equal to [John said ]) but then it doesn't know what the next character, 'H' is telling it to do.
There are a few ways to correct this, but your code does so by using single quotes and then replacing them with double quotes. The same line using that method is:
myvar = "John said 'Help'"
myvar = replace(myvar,chr(39), chr(34))
Here, the string originally has the desired sentence, but with single quotation marks around the word Help.
Chr(39) represents a single quotation mark and Chr(34) represents a double quotes. So the replace function changes all of the single quotation marks with double quotes.
Instead, you could have done this:
myvar = "John said " & chr(34) & "Help" & chr(34)
and it would have created the same string.
Your code sets the variable sFRM to the desired value with single quotes instead of double quotes and then replaces the single quotes with double quotes. The double quotes at the begining and end of the line of code are being used to denote that the letters inside them are to be put into a string.
The single quotation marks are being used as placeholders to be replaced. There are other ways to do this, but the method you have provided will work.
I'm trying to write an If then statement to see if a string has a space in it. If it does, I want it to put an " and " around the variable. Below is my current code:
If ColumnText.Contains(" ") Then
MsgBox(""" & ColumnText & """)
End If
Next
But it's seeing quoting everything... Any suggestions?
To properly escape a double quote inside VB's double quoted string literal, you need to double it (no pun intended). This means an empty string "". When you squeeze a quote in it, you get 4 quotes """", and this really means just one double quote literal.
You should be using:
MsgBox("""" & ColumnText & """")
Instead of:
MsgBox(""" & ColumnText & """)
Another thing - notice how the syntax parser highlights your line when it has 3 quotes. In this case & ColumnText & is part of the literal, instead of being an inline variable.
Reference:
String literals # MSDN.
Using quote literals makes for hard to read code and as seen here, can easily lead to errors. I find it much easier to use (and read) String.Format and isolate things you want to call out differently. For instance:
msg = String.Format("There is a problem with [{0}]", columnText)
The result: There is a problem with [foobar]
If you really like quotes, or need for something else like a command line argument, you can still make the code more legible this way:
Const quote As String = """"
' or
Private quote = Convert.ToChar(34) ' 34 is the code for the quote char
'...
msg = String.Format("There is a problem with {0}{1}{0}", quote, columnText)
The result: There is a problem with "foobar" In cases where there are multiple things to wrap with quotes, you just repeat {0} for each as shown.
You can try this:
If ColumnText.Contains(" ") Then
MsgBox(Chr(34) & ColumnText & Chr(34))
End If
Next
In following code, the usage of the string "“" (i.e. a left double quotation mark inside a string) results in a compile error in VB.NET:
StringVar = Replace(StringVar, "“", "“")
What’s going on here?
It seems as if you want to replace curly quotes with their HTML code equivalent.
On the first glance, your code is absolutely correct. The problem is that VB allows curly quotes in place of regular quotes in code (because Unicode is great, right?). That is, the following codes are all equivalent:
Dim str = "hello"
Dim str = “hello”
Dim str = "hello“
Now, if you want to use a quotation mark inside a string, VB doesn’t know whether the quotation mark is supposed to end the string or not. In C#, this would be fixed by escaping the quotation mark, i.e. in place of """ you’d write "\"". In VB, the same is done by doubling the quotation mark, i.e. """".
Back to your curly quote. The same as for straight quotes applies according to the VB language specification (¶1.6.4). So to write a curly quote in code, try the following:
StringVar = Replace(StringVar, "““", "“")
Unfortunately, I cannot try this code now and it’s altogether possible that the IDE simply replaces this by straight quotes. If that’s the case, an alternative is to use Chr or ChrW with the character code of the “left double quotation mark”:
StringVar = Replace(StringVar, ChrW(&H201C), "“")
Or, for symmetry, written in decimal (but I prefer hexadecimal for character codes):
StringVar = Replace(StringVar, ChrW(8220), "“")
Something else: the Replace function will probably soon be deprecated and doesn’t work everywhere (e.g. Windows Phone 7). Instead, use the Replace method of the String class:
StringVar = StringVar.Replace(, ChrW(8220), "“")
See http://msdn.microsoft.com/en-us/library/613dxh46%28v=vs.71%29.aspx
Try this:
StringVar = Replace(StringVar, "“", ChrW(&H8220))
It looks like you're searching for the ChrW function in the Microsoft.VisualBasic namespace, which is used to convert a Unicode character code into the actual character.
If you're trying to replace straight quotes in a string with curly quotes, try the following code:
'Declare a string that uses straight quotes
Dim origString As String = "This string uses ""quotes"" around a word."
'Create a new string by replacing the straight quotes from the original string
'with left-facing curly quotes
Dim newString As String = origString.Replace("""", ChrW(8220))
'Display the result
MessageBox.Show(newString)
Or, if you're trying to encode the left-facing curly quotes in a string by replacing them with an alternate notation (assuming the one you used in the question is correct), try the following code:
'Declare a string that uses left-facing curly quotes
Dim origString As String = "This string uses fancy " & ChrW(8220) & _
"quotes" & ChrW(8220) & " around a word."
'Create a new string by replacing the curly quotes with an arbitrary string
Dim newString As String = origString.Replace(ChrW(8220), "“")
'Display the result
MessageBox.Show(newString)
I am facing an issue with my code .
the thing is i want to escape { in the string.format function ...
Of course one way to escape it is to use {{ (2 curly braces)
Is there any other way possible to escape without using the double curly braces.
thanks
Why would there be another solution? {{ is specified as the way of escaping braces in a format string... I can't see why the API designers would include another way.
Of course, you could also provide a format parameter and then populate it with a brace:
Dim text as String = string.Format("{0}{1}", "{", "}")
will give "{}" as a string, for example... but I can't see that this is a better solution.
Perhaps if you could say why you dislike the normal solution (double curly braces) we could advise you on an alternative - but there isn't one within the format specification "language" itself, as far as I'm aware.
No, unfortunately it is not possible.
Well, you could do it this way, but not a good idea in my view.
Dim str1 As String = "Print this " & Chr(123) & "0" & Chr(125) & " string"
Dim str2 As String = "silly"
Console.WriteLine(String.Format(str1, str2))
Console.ReadLine()