I have the above data in row 1 (i.e. cell A1, cell B1, cell C1, etc).
I want to find the column number of the cell that contains Apr 2013.
Here’s my code:
MsgBox Application.Match("Apr 2013", Range("1:1"), 1)
which returns mismatch error. Any idea what went wrong?
You try this instead:
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
As Microsoft says:
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.
Therefore:
Sub ReadAboutFunctionsYouAreUsing()
Dim x
x = Array("Apr 2013", "Mar 2013", "Feb 2013")
MsgBox Application.Match("Apr 2013", x, 1)
End Sub
User Defined Function
in any cell type: =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
Answer:
I get this sort of thing in VBA a lot, especially with dates. Here’s what I would do:
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 = ""
For some reason, Match seems to like having a cell reference as its first parameter.
Tags: excel-vbaexcel, function, vba