【问题标题】:Converting Index Match to Another Sheet to VBA Code将索引匹配转换为另一个工作表到 VBA 代码
【发布时间】:2023-03-12 21:00:01
【问题描述】:

我正在尝试将索引匹配公式转换为 VBA 代码。我想这样做是因为包含索引匹配公式的单元格并不总是具有相同的行值,所以我不能简单地将公式放在特定的行中。该公式当前位于 H 列中,因此我尝试使用 VBA 代码来匹配另一张表中的值,并根据索引匹配条件将 H 列填充到正确的行中。

这是我的公式:

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

我最初尝试在 VBA 代码中调整为 V-Lookup,因为有人告诉我这会更容易,但我无法成功地做到这一点。我尝试的 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】:

    您的主要问题是这两行:

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

    h 返回错误或值,但您试图将其用作 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多