与excel VBA中的匹配函数不匹配
我在第1行中有上述数据(即单元格A1、单元格B1、单元格C1等) 我想找到包含2013年4月的单元格的列号 这是我的密码:与excel VBA中的匹配函数不匹配,excel,vba,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(Acti
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
正如上面所说: 因此:
Sub ReadAboutFunctionsYouAreUsing()
Dim x
x = Array("Apr 2013", "Mar 2013", "Feb 2013")
MsgBox Application.Match("Apr 2013", x, 1)
End Sub
用户定义函数
在任何单元格类型中:
=getColumnNumber(“2013年4月”)
我在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似乎喜欢将单元格引用作为其第一个参数。这可以转换为通用函数吗?用户定义函数?要返回列数?我修改了您编写的第一个代码,它可以正常工作。但是,我需要能够使用i的值来提取其他值。在VBA中-
Dim returnedValue&
然后新行returnedValue=getColumnNumber(“2013年2月”)
您的错误是因为需要使用WorksheetFunction.Match而不是Application.Match。但是@mehow的方法无论如何都更好
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
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 = ""