MATCH()函数在VBA中

美好的一天! 我试图运行下面的代码,但得到错误1004无法获得WorksheetFunction类的匹配属性 。 提前一点,根据我的理解,如果没有匹配,MATCH()函数返回#N / A ,所以没有必要将其分配给INDEXvariables(此外,我认为这也可能导致错误)。 你能build议如何修改代码来说明这种可能性吗?

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. 使用Application.Match而不是Application.WorksheetFunction.Match 。 该错误指示Match本身丢失,而不是Match的参数有问题。 (不知道为什么Match应该丢失,但!)

  2. 正如你在你的评论中提到的, Dim Index as Variant而不是Integer 。 (顺便说一下, 使用Long而不是Integer除非你调用一个16位API函数。)

  3. 根据这个答案 ,如果匹配失败( #N/A ), Application.Match返回错误Variant。 为了testing这个,使用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