Remove single quote VBA function

2019-07-26 04:51发布

To simplify, I have two sheets in an Excel workbook.

If I write =sheet2!R3C2 in one of the cells of sheet1, the cell takes the value of the cell R3C2 of sheet2 correctly. I would like to generalize that for many rows in VBA, so my code is:

row = XX a long 

temp = "=sheet2!R" & row - 1 & "C2"

Range("c" & row).Value = temp

But when I use this code, the value of the cell(row,3) is =sheet2!'RXXC2'

How can I remove the single quotes ??

3条回答
姐就是有狂的资本
2楼-- · 2019-07-26 05:30

You want to set the formula, not the value:

Range("c"&row).FormulaR1C1 = temp
查看更多
再贱就再见
3楼-- · 2019-07-26 05:31

try to write Range("c" & row).FormulaR1C1=temp

查看更多
唯我独甜
4楼-- · 2019-07-26 05:34
Range("C" & row).Formula = temp

would produce the correct formula in your cell.

What you should consider doing instead of looping is

Range("A1").Formula = "=Sheet2!$B1"
Range("A1").Resize(100, 1).Formula = Range("A1").Formula

The first line inserts a formula =Sheet2!$B1 in cell A1 of your active sheet. The $ dollar sign assures that the column will not be incremented (same applies with numbers)

Then the second line duplicates the formula across 100 rows down from A1 replacing the number after the B column

So now

A1 =Sheet2!B1
A2 =Sheet2!B2
A3 =Sheet2!B3
... 

Also, it's a bit unclear what you're trying to actually do so consider another option which is saving the value of formula into another range using the Evaluate() function

Range("c" & row).Value = Evaluate(temp) Or Range("C" & Row).Value = [temp]

查看更多
登录 后发表回答