Application.WorksheetFunction.Match方法

时间:2013-11-26 10:32:12

标签: excel-vba vba excel

我见过很多关于“无法获取工作表类的匹配属性”问题的主题。但我无法修复我的代码。

为什么这段代码不起作用?

rowNum = Application.WorksheetFunction.Match(aNumber, Sheet5.Range("B16:B615"), 0)

但是这段代码可以运行几行:

rowNum2 = Application.WorksheetFunction.Match(originCode, Sheet7.Range("B10:B17"), 0)

我的两行之间的唯一区别是在rowNum2中我使用String查找并在rowNum中使用整数。 查找Value是否可能需要为String?

@Update on my Problem

Select Case service
Case "Low Cost"
MsgBox Sheet5.Cells(16, "B") 'Gets value 0.5
Set Rng = Sheet5.Range("B16:B615")

   If Not IsError(Application.Match("0.5", Rng, 0)) Then 'But jumps to Else
    rowNum = Application.Match(Weight, Rng, 0) 'Weight = 0.5
    MsgBox rowNum
Else
    MsgBox "error"
End If



Case "Standard"

Case "Express"

Case Else

End Select

@UPDATE 2

!!!注意“0.5”是一个字符串,而不是0.5 所以0.5不是“0.5”(这是我在代码中的错误)

1 个答案:

答案 0 :(得分:15)

您收到此错误,因为无法在范围内找到该值。字符串或整数无关紧要。根据我的经验,最好的办法是先检查一下是否存在该值。

我在下面使用了CountIf,但是有很多不同的方法可以检查范围内是否存在值。

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

替代方式

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub