【问题标题】:Combining R1C1 in vba with a dynamic range将 vba 中的 R1C1 与动态范围相结合
【发布时间】:2025-11-30 17:30:01
【问题描述】:

我正在尝试在sheets("formula").range("D3") 中使用vlookup 并将其自动填充到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”:应用程序定义或对象定义错误。

任何帮助将不胜感激

【问题讨论】:

  • 在第三个 With 块中,您使用的是 lastrow 而不是 comlast
  • 谢谢!没能捡到。我已经更正了,但仍然出现同样的错误
  • 现在您需要在分配公式之前调试和检查这三个值。
  • 你还需要qualify嵌套Cells(lastrow, lastcol)与工作表对象。
  • 你在哪一行得到错误?

标签: vba excel


【解决方案1】:

我会更改以下内容:

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

【讨论】:

  • @Ian 如果这仍然不起作用,您可能必须使用 .Range(Cells(last Row,last Col).Address) 而不是 .cells(last Row,last Col)跨度>
  • 在 Scott 和 GSerg 的帮助下让它工作,但我会查找 .address 以供将来参考
  • @Ian 别担心