转换索引匹配到另一个工作表到VBA代码

问题描述 投票:0回答:1

我想翻译的索引匹配公式为VBA代码。我想这样做,因为这包含索引匹配公式的单元格不会总是具有相同的行值,所以我不能简单地将公式特定行。式是目前在H列,所以我想有VBA代码,将来自另一片的值相匹配,以及基于所述索引匹配准则正确的行中填充H列。

这里是我的公式:

=IFERROR(INDEX(Comments!$K$2:$K$76,MATCH(C8,Comments!$B$2:$B$76,0)),"COMMENT REQUIRED")

我最初尝试适应是一个V-查找在VBA代码,有人告诉我,这将是比较容易的,但我一直没能成功地做到这一点。我尝试的VBA代码如下:

        Dim h
        With DestinationSheet.Rows(DestinationRow)
        h = Application.VLookup(.Cells(3).Value, Sheets("Comments").Range("$A$2:$C$100"), 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
excel vba excel-2016
1个回答
1
投票

你的主要问题是这两条线:

    .Cells(8).Font.Color = IIf(IsError(h), RGB(255, 0, 0), h)
    .Cells(8).Font.Bold = IIf(IsError(h), True, h)

h返回错误或值,但是你要使用它作为一个RGB颜色和一个布尔值。 h不能在同一时间所有的三件事情。

之前捕获错误,如果然后使用标准

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
© www.soinside.com 2019 - 2024. All rights reserved.