VBA中的MATCH()函数

时间:2016-07-15 14:13:41

标签: excel vba excel-vba excel-2010 worksheet-function

美好的一天!我正在尝试运行下面的代码,但得到错误1004 无法获取WorksheetFunction类的Match属性。提前一点,据我所知,如果没有匹配,MATCH()函数返回 #N / A ,所以没有必要将它分配给INDEX变量(此外,我认为它也可能导致错误)。您能否建议如何修改代码以解释这种可能性?

Sub Debugging()

Workbooks("Problem.xls").Worksheets(1).Activate

Cash_Rows = 5
Share_Rows = 6

If Cash_Rows <= Share_Rows Then

Range("A1:A" & Cash_Rows).Select
With Selection.Interior
    .ThemeColor = xlThemeColorAccent6
    .TintAndShade = 0.399975585192419 
End With

Count_Cash = Application.WorksheetFunction.CountIf(Range("A:A"), "L*")

For Each cell In Range("A1:A" & Cash_Rows)
    If CStr(cell.Value) Like "L*" Then
    Range("A" & cell.Row & ":" & "D" & cell.Row).Interior.Color = 65535
    Dim Index As Integer
    Index = Application.WorksheetFunction.Match(CStr(cell.Value), Range("F2:" & "F" & Share_Rows), 0)
    Range("F" & Index & ":" & "I" & Index).Interior.Color = 65535
    End If
Next

If Count_Cash = 0 Then
    MsgBox "You do not have any matching ID+Amount between Cash and Shares booking. It's OK!"
Else
    MsgBox "You have " & Count_Cash & " matching transactions. Check them!"
End If 

Else 

MsgBox "Do not worry. Be happy!" 

End If 

End Sub

提前谢谢!

1 个答案:

答案 0 :(得分:1)

  1. 使用Application.Match代替Application.WorksheetFunction.Match。该错误表明Match本身缺失,而不是Match的参数存在问题。 (不知道为什么Match应该丢失!)

  2. 正如您在评论中提到的,Dim Index as Variant而不是Integer。 (顺便提一下,use Long instead of Integer除非您正在调用仅限16位的API函数。)

  3. 如果匹配失败(Application.Match),则每this answer#N/A会返回错误Variant。要测试它,请使用IsError

    If Not IsError(Index) Then
        Dim idxstr as String: idxstr = CStr(Index)
            ' ^^ Make sure you don't get surprised by how the Variant converts
        Range("F" & idxstr & ":" & "I" & idxstr).Interior.Color = 65535
    End If