Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When writing string to a cell, VBA inserts extra single quotation marks

Tags:

excel

vba

I am trying to write this formula using VBA:

ActiveCell.Value = "=f(R[-1]C[0],Sheet1!" & ColumnLetter & i & ")"

Where ColumnLetter is some variable letter which my macro computes earlier, and f is some function, and i is some number.

The problem is that when I run this, the cell is given this instead: (if ColumnLetter = F, i = 16):

=f(R[-1]C[0],Sheet1!'F16')

but I want:

=f(R[-1]C[0],Sheet1!F16)

Why is VBA or Excel putting those single quotation marks around F16? It does not insert these extra quotation marks if I do not include R[-1][0] as an argument in my formula, but I need to include this.

Help much appreciated!

like image 388
Derek Avatar asked Oct 17 '11 07:10

Derek


People also ask

How do you escape a single quote in VBA?

Escape Character in VBA In programming languages “\” — a backslash — is generally used as an escape character.

How do you handle double quotes in VBA?

You need to double up on the double quotes inside the string, otherwise it looks to VBA like you are ending the string because there's a single " in the middle of the string.

How do I change quotation marks in VBA?

Cells. Replace What:="", Replacement:="", LookAt:=xlPart, MatchCase:=False 'Replaces the quotes.

How do you add a string to a cell in VBA?

To concatenate two strings using a VBA code, you need to use the ampersand. You can use an ampersand in between two strings to combine them and then assign that new value to a cell, variable, or message box. In the same way, you can concatenate more than two values as well.


2 Answers

Its the combination of R1C1 and A1 addressing. You need to pick one method and use it for both parts.
Note that if you type =f(R[-1]C[0],Sheet1!F16) into a cell you will get an error for the same reason.

You say you need to use R1C1 style for the first address, but (assuming this is because you don't want absolute address) you can use .Offset instead

ActiveCell.Value = "=f(" & ActiveCell.Offset(-1, 0).Address(False, False) _
 & ",Sheet1!" & ColumnLetter & i & ")"
like image 128
chris neilsen Avatar answered Sep 18 '22 02:09

chris neilsen


The Apostrophe means to Excel that it should interpret it as text.

Write it to ActiveCell.Formula. That way it is recognized as Formula.

like image 35
Delcon Avatar answered Sep 21 '22 02:09

Delcon