将vba中的R1C1与动态范围相结合

时间:2017-12-26 17:33:46

标签: vba excel-vba excel

我正在尝试在vlookup中使用sheets("formula").range("D3")并将其自动填充到D3与sheets("formula")中最后一行和最后一列中的单元格之间的所有单元格中。查找值位于sheets("combined")中,其在数量或行数方面具有动态范围。到目前为止,这是我的代码:

Sub Vlookup ()
    Dim lastcol As Integer
    With Sheets("Formula")
        lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With

    Dim lastrow As Long
    With Sheets("Formula")
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim comlast As Long
    With Sheets("Combined")
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Sheets("Formula").Range("D2").FormulaR1C1 = "=IFERROR(VLOOKUP(RC3&"" | ""&R1C,Combined!R2C3:R" & comlast & "C4, 2, FALSE),"" "")"
    Sheets("Formula").Range("D2").AutoFill Destination:=Sheets("Formula").Range("D2:D" & lastrow), Type:=xlFillDefault
    Sheets("Formula").Range("D2:D" & lastrow).AutoFill Destination:=Sheets("Formula").Range(Cells(2, "D"), Cells(lastrow, lastcol)), Type:=xlFillDefault
End Sub

我收到运行时错误'1004':应用程序定义或对象定义错误。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我会更改以下内容:

Dim comlast As Long
With Sheets("Combined")
    Comlast = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

With Sheets("Formula")
    .Range("D2").FormulaR1C1 = "=IFERROR(VLOOKUP(RC3&"" | ""&R1C,Combined!R2C3:R" & comlast & "C4, 2, FALSE),"" "")"
    .Range("D2").AutoFill Destination:=.Range("D2:D" & lastrow), Type:=xlFillDefault
    .Range("D2:D" & lastrow).AutoFill Destination:=.Range(Cells(2, "D"), .Cells(lastrow, lastcol)), Type:=xlFillDefault
End With