Excel VBA - application.worksheetfunction.match中的错误

时间:2014-11-19 10:33:52

标签: excel vba

我真的对此感到失望,所以如果有人花时间帮忙,我将不胜感激!

我怀疑我的问题源于不正确的变量声明,但我无法解决这个问题。

那么为什么这个测试程序有效:

Sub testmatch3()

    Dim arr()           As Variant
    Dim num             As Long
    Dim searchVal       As Variant
    Dim i               As Long

    ReDim arr(1 To 10)

    For i = 1 To 10
        arr(i) = i
    Next i

    searchVal = 4
    Debug.Print getMatch(searchVal, arr)

End Sub

Function getMatch(valueToMatch As Variant, matchArr As Variant) As Long

    getMatch = Application.WorksheetFunction.Match(valueToMatch, matchArr, 0)

End Function

但是下面给出了一个不匹配错误(类型13):

Sub NewProcedure()

    Dim ENVarr              As Variant
    Dim StageRange          As Range
    Dim cell                As Range
    Dim LastRow             As Long
    Dim i                   As Long
    Dim ConnSheet           As Worksheet
    Dim tempstring          As Variant
    Dim arr()               As Variant

    Set ConnSheet = ThisWorkbook.Sheets("L1 forces")

    ' Find the last used row in the sheet and define the required ranges
    LastRow = ConnSheet.Range("A11").End(xlDown).row
    Set StageRange = ConnSheet.Range("H11:H" & LastRow)

    ' I have a big table of data in the "ENV sheet" which I transfer into a large 2D array
    ENVarr = ThisWorkbook.Worksheets("ENV").Range("A6").CurrentRegion

    ' From the ENVarray, make its second column into a new 1D array
    ' This new array has an upper bound dimension equal to the number of rows in ENVarr
    ReDim arr(LBound(ENVarr, 1) To UBound(ENVarr, 1))
    For i = LBound(arr) To UBound(arr)
        arr(i) = ENVarr(i, 2)
    Next i

    tempstring = "1140"
    Debug.Print getMatch(tempstring, arr)

End Sub

Function getMatch(valueToMatch As Variant, matchArr As Variant) As Long

    getMatch = Application.WorksheetFunction.Match(valueToMatch, matchArr, 0)

End Function

请注意,arr!中确实存在值“1140”

由于

1 个答案:

答案 0 :(得分:0)

我想你的表中的数字是1140,你试着匹配字符串" 1140"。你有没有尝试写

tempstring = 1140

没有引号?

或者:确保excel表中确实存在一个字符串:="1140",它不仅格式化为字符串。 =TYPE(cell)('单元格'包含您的1140)的返回值必须为2