VBA宏:预期语句结尾的编译错误

时间:2018-09-07 01:12:19

标签: excel vba excel-vba

我正在尝试使用基于唯一案例ID的索引匹配将数据从源工作簿复制到目标工作簿。

thisworkbook.Worksheets("Check").range("B2:B" & lastRowDash).value = "=IFERROR(Index(src.Worksheets("Sheet1").range("B:B"), MATCH(ThisWorkbook.Worksheets("Check").range("A2").value, src.Worksheets("Sheet1").range("A:A")), 0), 0), ""Closed"")"

按下Enter键后,我会收到一个编译错误

1 个答案:

答案 0 :(得分:2)

将.Address与external:= true一起使用,可以将VBA工作簿/工作表/范围引用转换为工作表公式引用。

thisworkbook.Worksheets("Check").range("B2:B" & lastRowDash).FORMULA = _
  "=IFERROR(INDEX(" & src.Worksheets("Sheet1").range("B:B").Address(external:=true) & ", MATCH(" & ThisWorkbook.Worksheets("Check").range("A2").Address(0, 0, external:=true) & ", " & src.Worksheets("Sheet1").range("A:A").Address(external:=true) & ", 0)), ""Closed"")"

如果您将各种地址分配给变量,则可能更容易理解。

dim addr1 as string, addr2 as string, addr3 as string

addr1 = src.Worksheets("Sheet1").range("B:B").Address(external:=true)
addr2 = ThisWorkbook.Worksheets("Check").range("A2").Address(0, 0, external:=true)
addr3 = src.Worksheets("Sheet1").range("A:A").Address(external:=true)

thisworkbook.Worksheets("Check").range("B2:B" & lastRowDash).FORMULA = _
  "=IFERROR(INDEX(" & addr1 & ", MATCH(" & addr2 & ", " & addr3 & ", 0)), ""Closed"")"