簡體   English   中英

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

[英]Mismatch with match function in excel VBA

在此輸入圖像描述

我在第1行中有上述數據(即單元格A1,單元格B1,單元格C1等)。

我想找到包含2013年4月的單元格的列號。

這是我的代碼:

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

返回不匹配錯誤。 知道出了什么問題嗎?

你試試這個:

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



正如微軟所說:

 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 

我在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似乎喜歡將單元格引用作為其第一個參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM