How to pass an integer variable into a vba formula

2019-03-05 01:41发布

I am having a bit of trouble with this code that I have written:

Sub lol()

Dim counter As Integer

counter = 1

Do Until Selection.Value = ""
    Dim ws As Worksheet
    Sheets("Row1").Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
    Set ws = ActiveSheet



    Sheets("Sheet1").Select
    ws.Name = "Row " + CStr(ActiveCell.Value)
    Set newSelection = ActiveCell.Offset(1, 0)

    ws.Select
    ActiveCell.FormulaR1C1 = "=Sheet1!R[counter]C[1]"
    ws.Range("A1").Select
    Selection.AutoFill Destination:=ws.Range("A1:C1"), Type:=xlFillDefault
    ws.Range("A1:C1").Select
    Sheets("Sheet1").Select
    newSelection.Select

    counter = counter + 1

    Loop

    ActiveCell.Offset(-1, 0).Select

    MsgBox ("All sheets updated")


End Sub

I get an error when running this line:

ActiveCell.FormulaR1C1 = "=Sheet1!R[counter]C[1]"

But I am not sure why. I defined that variable as an integer and so I do not understand why it won't work. If I remove the counter, and instead just write "=Sheet1!R[1]C[1]" it works fine, so I know the thing in there has to be an integer. (Problem with that in particular is that it will always be the same row, but I need it to drop one row for each iteration, which is why I created the counter variable, but don't really get why it won't work. Any thoughts? (Is it that I have defined the variable type incorrectly, or is this just not the right semantically to do what I am trying to do?)

1条回答
可以哭但决不认输i
2楼-- · 2019-03-05 02:12

The reference to 'counter' needs to be outside the quotations:

ActiveCell.FormulaR1C1 = "=Sheet1!R[" & counter & "]C[1]"
查看更多
登录 后发表回答