如何在VBA中的一系列单元格中复制R1C1公式

时间:2021-04-21 04:33:33

标签: excel vba

我正在尝试将 R1C1 公式复制到一系列单元格。但我收到错误运行时 1004。

代码如下:

Dim cell_range As String
cell_range = "E126:E146"
Formula = Application.ConvertFormula( _
                                    Formula:=Formula, _
                                    fromReferenceStyle:=xlR1C1, _
                                    toReferenceStyle:=xlA1)
wk_sht.range(cell_range).FormulaR1C1 = Formula

原始公式为:

=IF(C126="","",IF(SIZE_CHECK=TRUE,IF('Sheet1'!L14<>"",'Sheet2'!M14,"TBA"),""))

转换为 R1C1 后的公式为:

=IF($DV:$DV="","",IF(SIZE_CHECK=TRUE,IF('[Excel.xlsm]Sheet1'!'L14'<>"",'[Excel.xlsm]Sheet2'!'M14',"TBA"),""))

使用这行代码:

Formula = Application.ConvertFormula( _
                                    Formula:=Formula, _
                                    fromReferenceStyle:=xlR1C1, _
                                    toReferenceStyle:=xlA1)

1 个答案:

答案 0 :(得分:0)

假设这是您要转换为 R1C1 的公式,

=IF(C126="","",IF(SIZE_CHECK=TRUE,IF('Sheet1'!L14<>"",'Sheet2'!M14,"TBA"),""))

试试这个代码。

更改 Sheets("Sheet1") 以引用您希望公式继续运行的工作表。

Sub InsertFormula()
Dim wk_sht As Worksheet
Dim cell_range As String
Dim strFormulaA1 As String
Dim strFormulaR1C1 As String

    Set wk_sht = Sheets("Sheet1")
    
    cell_range = "E126:E146"
    
    strFormulaA1 = "=IF(C126="""","""",IF(SIZE_CHECK=TRUE,IF('Sheet1'!L14<>"""",'Sheet2'!M14,""TBA""),""""))"
    
    strFormulaR1C1 = Application.ConvertFormula( _
                                    Formula:=strFormulaA1, _
                                    fromReferenceStyle:=xlA1, _
                                    toReferenceStyle:=xlR1C1)
                                    
    wk_sht.Range(cell_range).FormulaR1C1 = strFormulaR1C1
    
End Sub