VBA:无法获取 WorkSheet 函数类的 Match 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18211920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:44:09  来源:igfitidea点击:

VBA: Unable to get the Match property of the WorkSheet function class

excelvba

提问by mezamorphic

Could someone please advise with the below code. I'd like to be able to find the column in which "Index" appears:

有人可以用下面的代码提供建议。我希望能够找到出现“索引”的列:

Sub Test()
    Dim d As Range
    Dim a As Variant

    Set d = Sheet2.Range("H349:M349")

    a = Application.WorksheetFunction.Match("Index", d, 0)

End Sub

But I get an error on the last line saying:

但我在最后一行收到错误消息:

Unable to get the Match property of the WorkSheet function class

无法获取 WorkSheet 函数类的 Match 属性

回答by tigeravatar

Are you sure the word "Index" (and only "Index") appears by itself in one of the cells within Sheet2 (which may not necessary be the same as Sheets("Sheet2")) H349:M349?

您确定“索引”这个词(并且只有“索引”)单独出现在 Sheet2 中的一个单元格中(它可能不需要与 Sheets("Sheet2") 相同)H349:M349?

Match can be rather error prone in VBA, so I prefer to use the Range.Find method instead, which can be tested for Nothing (wasn't found):

Match 在 VBA 中可能相当容易出错,所以我更喜欢使用 Range.Find 方法,该方法可以测试为 Nothing(未找到):

Sub Test()

    Dim rngFound As Range

    Set rngFound = Sheet2.Range("H349:M349").Find("Index", , xlValues, xlWhole)
    If Not rngFound Is Nothing Then
        'Found a match
        MsgBox "Found a match at " & rngFound.Address
    Else
        'No matches
        MsgBox "No matches"
    End If

End Sub