1

ここに画像の説明を入力

行1に上記のデータがあります(つまり、セルA1、セルB1、セルC1など)。

2013 年 4 月を含むセルの列番号を見つけたいです。

これが私のコードです:

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

不一致エラーを返します。何がうまくいかなかったのですか?

4

2 に答える 2

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



マイクロソフトが言う ように:

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
于 2013-05-16T10:38:21.403 に答える
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 は最初のパラメーターとしてセル参照を持つことを好むようです。

于 2014-10-23T02:22:40.457 に答える