将索引匹配转换为动态 VBA 代码

Converting Index Match to Dynamic VBA Code

我有一个索引匹配方程,我正试图将其转换为 VBA 代码:

=IFERROR(INDEX(Comments!$C:$C0,MATCH(C8,Comments!$A:$A0,0)),"COMMENT REQUIRED")

这是我想出的:

DestinationSheet.Cells(DestinationRow, 8).Value = Application.WorksheetFunction.Index(Sheets("Comments").Range("$C:$C0"), Application.WorksheetFunction.Match((DestinationSheet.Range(DestinationRow, 3)), Sheets("Comments").Range("$A:$A0"), 0), 1)

但是,我遇到了一个错误。本质上,第一个公式根据 C 列中的值找到位于另一个 sheet 中的值。

对于第二位代码,我试图查看另一个 sheet 中的相同值,但基于定义为 DestinationRow 的行的第 3 列中的值。我在 VBA 代码中这样做是因为被索引匹配的条目的行号是未知的,这就是为什么我必须使用 DestinationRow 来指定行,而不是像第一个公式中那样对值进行硬编码。

VLOOKUP 似乎没那么复杂:

Dim m
With DestinationSheet.Rows(DestinationRow)
    m = Application.VLookup(.Cells(3).Value, Sheets("Comments").Range("$A:$C0"), 3, False)
    .Cells(8).Value = IIf(IsError(m), "COMMENT REQUIRED", m)
End With

注意:在VBA

中有两种不同的工作表函数使用方式

这个:

Application.Worksheetfunction.VLookup(...)

如果没有匹配项,将引发 运行 次错误,您需要捕获并处理。

这个:

Application.VLookup(...)

不会 引发 运行 次错误,而是 return 一个错误值,您可以使用 IsError()[ 测试该错误值=14=]