与excel VBA中的匹配功能不匹配

时间:2013-05-16 10:26:13

标签: excel-vba vba excel

enter image description here

我在第1行中有上述数据(即单元格A1,单元格B1,单元格C1等)。

我想找到包含2013年4月的单元格的列号。

这是我的代码:

MsgBox Application.Match("Apr 2013", Range("1:1"), 1)

返回不匹配错误。知道出了什么问题吗?

2 个答案:

答案 0 :(得分:2)

你试试这个:

Sub main()
    Dim stringToMatch$
    stringToMatch = "Apr 2013"
    Call DisplayMatchingColumnNumber(ActiveSheet, stringToMatch)
End Sub

Sub DisplayMatchingColumnNumber(ByRef ws As Worksheet, str$)
Dim i&, x$
    For i = 1 To ws.Cells(1, Columns.Count).End(xlToLeft).Column
        x = Right(CStr(ws.Cells(1, i).Value), 8)
        If StrComp(x, str, vbTextCompare) = 0 Then
            MsgBox "the column number is: " & i
        End If
    Next i
End Sub

<小时/> <小时/> 正如Microsoft所说:

Arg2 is Required of type Variant 
Lookup_array - a contiguous range of cells containing possible lookup values. 
Lookup_array must be an array or an array reference.

因此:

Sub ReadAboutFunctionsYouAreUsing()
    Dim x
    x = Array("Apr 2013", "Mar 2013", "Feb 2013")
    MsgBox Application.Match("Apr 2013", x, 1)
End Sub

<小时/> <小时/> 用户定义的功能
在任何单元格类型中:=getColumnNumber("Apr 2013")

Function getColumnNumber(str$)
    Dim i&, x$
    For i = 1 To ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
        x = Right(CStr(ActiveSheet.Cells(1, i).Value), 8)
        If StrComp(x, str, vbTextCompare) = 0 Then
            getColumnNumber = i
        End If
    Next i
End Function

答案 1 :(得分:1)

我在VBA中经常遇到这种情况,尤其是日期。这就是我要做的事情:

Dim tmpRng As Range
Set tmpRng = ActiveWorkbook.Worksheets("Sheet1").Range("AA:650") 'or some other unused cell
tmpRng.Value = "Apr 2013"
MsgBox Application.Match(tmpRng, Range("1:1"), 1)
tmpRng.Value = ""

出于某种原因,Match似乎喜欢将单元格引用作为其第一个参数。