将索引匹配转换为另一个 Sheet 到 VBA 代码
Converting Index Match to Another Sheet to VBA Code
我正在尝试将索引匹配公式转换为 VBA 代码。我想这样做是因为包含索引匹配公式的单元格不会总是具有相同的行值,所以我不能简单地将公式放在特定的行中。该公式当前位于 H 列中,因此我尝试使用 VBA 代码来匹配另一个 sheet 中的值,并根据索引匹配条件将 H 列填充到正确的行中。
这是我的公式:
=IFERROR(INDEX(Comments!$K:$K,MATCH(C8,Comments!$B:$B,0)),"COMMENT REQUIRED")
我最初尝试适应成为 VBA 代码中的 V-Lookup,因为有人告诉我这会更容易,但我未能成功做到这一点。我试过的 VBA 代码如下:
Dim h
With DestinationSheet.Rows(DestinationRow)
h = Application.VLookup(.Cells(3).Value, Sheets("Comments").Range("$A:$C0"), 3, False)
.Cells(8).Value = IIf(IsError(h), "COMMENT REQUIRED", h)
.Cells(8).Font.Color = IIf(IsError(h), RGB(255, 0, 0), h)
.Cells(8).Font.Bold = IIf(IsError(h), True, h)
End With
你的主要问题是这两行:
.Cells(8).Font.Color = IIf(IsError(h), RGB(255, 0, 0), h)
.Cells(8).Font.Bold = IIf(IsError(h), True, h)
h
returns 错误或值,但您正试图将其用作 RGB 颜色和布尔值。 h
三个东西不能同时存在。
捕获之前的错误并使用标准 IF Then
Dim DestinationSheet As Worksheet
Set DestinationSheet = Worksheets("Sheet1") 'change to your sheet
Dim cmmtsSheet As Worksheet
Set cmmtsSheet = Worksheets("Comments")
Dim DestinationRow As Long
DestinationRow = 3
With DestinationSheet
Dim mtchRow As Long
On Error Resume Next
mtchRow = Application.Match(.Cells(DestinationRow, 3), cmmtsSheet.Range("A:A"), 0)
On Error GoTo 0
With .Cells(DestinationRow, 8)
If mtchRow > 0 Then
.Value = cmmtsSheet.Cells(mtchRow, 3)
.Font.Color = RGB(255, 255, 255)
.Font.Bold = False
Else
.Value = "Comment Required"
.Font.Color = RGB(255, 0, 0)
.Font.Bold = True
End If
End With
End With
我正在尝试将索引匹配公式转换为 VBA 代码。我想这样做是因为包含索引匹配公式的单元格不会总是具有相同的行值,所以我不能简单地将公式放在特定的行中。该公式当前位于 H 列中,因此我尝试使用 VBA 代码来匹配另一个 sheet 中的值,并根据索引匹配条件将 H 列填充到正确的行中。
这是我的公式:
=IFERROR(INDEX(Comments!$K:$K,MATCH(C8,Comments!$B:$B,0)),"COMMENT REQUIRED")
我最初尝试适应成为 VBA 代码中的 V-Lookup,因为有人告诉我这会更容易,但我未能成功做到这一点。我试过的 VBA 代码如下:
Dim h
With DestinationSheet.Rows(DestinationRow)
h = Application.VLookup(.Cells(3).Value, Sheets("Comments").Range("$A:$C0"), 3, False)
.Cells(8).Value = IIf(IsError(h), "COMMENT REQUIRED", h)
.Cells(8).Font.Color = IIf(IsError(h), RGB(255, 0, 0), h)
.Cells(8).Font.Bold = IIf(IsError(h), True, h)
End With
你的主要问题是这两行:
.Cells(8).Font.Color = IIf(IsError(h), RGB(255, 0, 0), h)
.Cells(8).Font.Bold = IIf(IsError(h), True, h)
h
returns 错误或值,但您正试图将其用作 RGB 颜色和布尔值。 h
三个东西不能同时存在。
捕获之前的错误并使用标准 IF Then
Dim DestinationSheet As Worksheet
Set DestinationSheet = Worksheets("Sheet1") 'change to your sheet
Dim cmmtsSheet As Worksheet
Set cmmtsSheet = Worksheets("Comments")
Dim DestinationRow As Long
DestinationRow = 3
With DestinationSheet
Dim mtchRow As Long
On Error Resume Next
mtchRow = Application.Match(.Cells(DestinationRow, 3), cmmtsSheet.Range("A:A"), 0)
On Error GoTo 0
With .Cells(DestinationRow, 8)
If mtchRow > 0 Then
.Value = cmmtsSheet.Cells(mtchRow, 3)
.Font.Color = RGB(255, 255, 255)
.Font.Bold = False
Else
.Value = "Comment Required"
.Font.Color = RGB(255, 0, 0)
.Font.Bold = True
End If
End With
End With