Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel (2007) VBA - .Formula with quotes in it

I tried putting the following code into a program yesterday. VBA called an error. I assume it is because of the double quotes inside the formula. I googled and all results I found just gave the basic of putting formulas in, but none explained how to get around quotes inside.

(there was a With statement before this, Pivot is a worksheet name)

.Range("A2").Formula = "=IF(Pivot!A5="",A1,Pivot!A5)" 

Any help is much appreciated. Thanks!

like image 938
GeoffDS Avatar asked Apr 13 '12 14:04

GeoffDS


People also ask

How do you put quotation marks in VBA?

Strings in VBA are delimited with quotation marks. If you want to include quotation marks in your string, you need to double them. Otherwise, the VBA compiler will not recognize that they should not end the string. aStringVariable = "The word ""quotes"" is in quotes."

How do I put double quotes in a string in VBA?

I find the easiest way is to double up on the quotes to handle a quote. *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.

How do you escape quotes in Excel?

To include double quotes inside a formula, you can use additional double quotes as escape characters. By escaping a character, you are telling Excel to treat the " character as literal text. You'll also need to include double quotes wherever you would normally in a formula.


3 Answers

Whenever in doubt, record a macro if it allows :)

Try this

.Range("A2").Formula = "=IF(Pivot!A5="""",A1,Pivot!A5)" 
like image 188
Siddharth Rout Avatar answered Oct 06 '22 00:10

Siddharth Rout


Use Chr(34) in place of a double-quote.

So in your case:

.Range("A2").Formula = "=IF(Pivot!A5=" & Chr(34) & Chr(34) & ",A1,Pivot!A5)"
like image 33
Marc Avatar answered Oct 06 '22 00:10

Marc


you might need to do this:

.Range("A2").Formula = "=IF(Pivot!A5="& """" & """" & ",A1,Pivot!A5)" 
like image 1
Greg Avatar answered Oct 06 '22 01:10

Greg