简体   繁体   中英

Excel VBA - Runtime error '1004'

I have some VBA code where I want to copy a formula into a range of cells using R1C1 . Unfortunately I get the following error on the second to last line:
Runtime error '1004': Application-defined or object-defined error.

Dim pct As Single
pct = 1

With ThisWorkbook.Sheets("Data").UsedRange
    Dim lastR As Long
    lastR = .Rows.Count 
    Dim lastC As String
    lastC = col_letter(.Columns.Count)
End With

With ThisWorkbook.Sheets("Calculations")
    .Range("A1:" & lastC & 1).Value = 100
==> .Range("A2:" & lastC & lastR + 1).FormulaR1C1 = "=R[-1]C*(1+" & pct / 100 & "*'Data'!R[-1]C"
End With

What am I doing wrong here?

您在公式中可能缺少括号

"=R[-1]C*(1+" & pct / 100 & ")*'Data'!R[-1]C"

I think you are running non-english version of Excel/Office. Therefore there could be a problem of numbers separation mark. It's required to use . (dot) . (dot) in function defined as string and passed then by formulaR1C1 property to Excel. It will be then converted into , (comma) which is required when putting function in excel cell. Therefore this lines works for me with no error:

....=Replace("=R[-1]C*(1+" & pct / 100 & ")*Data!R[-1]C", ",", ".")

One more thing, I removed '' (single quotation marks) for sheet name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM