vba WorksheetFunction.Match 搜索多个值
vba WorksheetFunction.Match search for multiple values
我目前正在 HR sheet 中搜索包含特定文本的列 header。此文本每周都可能更改,例如,一个名为“State/Province”的列可能有一周没有 space,但下一周可能是“州/省”(注意单词之间的space)。
我目前正在使用下面的代码来寻找一个条件
StateProvince = WorksheetFunction.Match("State/Province", hr.Sheets("Open").Rows(1), 0)
这工作正常,但我希望添加到此,以便它查找包含 spaces 的第二个示例(如果列 header 是这种情况)。有什么建议吗?
使用:
StateProvince = WorksheetFunction.Match("State*/*Province", hr.Sheets("Open").Rows(1), 0)
这个答案是针对您的问题的。如果您想要更通用的解决方案,则必须提供其他示例。
由于空格的出现不可预测,您最好通过自定义 MyMatch()
函数完全忽略它们,向其传递 "unspaced" 字符串,如下所示:
Function MyMatch(textToSearch As String, rng As Range) As Long
Dim txtRng As Range, cell As Range
MyMatch = -1 '<--| default value for no match found
On Error Resume Next
Set txtRng = rng.SpecialCells(xlCellTypeConstants, xlTextValues) '<--| consider only cells with text values
On Error GoTo 0
If Not txtRng Is Nothing Then '<--| If there's at least one cell with text value
For Each cell In txtRng '<--| loop through selected "text" cells
If WorksheeyFunction.Substitute (cell.Value, " ", "") = textToSearch Then '<--|remove every space occurrence from cell value and compare it to your "nospace" searched value
MyMatch = cell.Column - rng.Columns(1).Column + 1
Exit For
End If
Next cell
End If
End With
使用方法如下:
Dim StateProvince As Long
StateProvince = MyMatch("State/Province", hr.Sheets("Open").Rows(1)) '<--| pass an "unspaced" string to search
If StateProvince > 0 Then
' code for handling found StateProvince
Else
' code for handling NOT found StateProvince
End If
我目前正在 HR sheet 中搜索包含特定文本的列 header。此文本每周都可能更改,例如,一个名为“State/Province”的列可能有一周没有 space,但下一周可能是“州/省”(注意单词之间的space)。
我目前正在使用下面的代码来寻找一个条件
StateProvince = WorksheetFunction.Match("State/Province", hr.Sheets("Open").Rows(1), 0)
这工作正常,但我希望添加到此,以便它查找包含 spaces 的第二个示例(如果列 header 是这种情况)。有什么建议吗?
使用:
StateProvince = WorksheetFunction.Match("State*/*Province", hr.Sheets("Open").Rows(1), 0)
这个答案是针对您的问题的。如果您想要更通用的解决方案,则必须提供其他示例。
由于空格的出现不可预测,您最好通过自定义 MyMatch()
函数完全忽略它们,向其传递 "unspaced" 字符串,如下所示:
Function MyMatch(textToSearch As String, rng As Range) As Long
Dim txtRng As Range, cell As Range
MyMatch = -1 '<--| default value for no match found
On Error Resume Next
Set txtRng = rng.SpecialCells(xlCellTypeConstants, xlTextValues) '<--| consider only cells with text values
On Error GoTo 0
If Not txtRng Is Nothing Then '<--| If there's at least one cell with text value
For Each cell In txtRng '<--| loop through selected "text" cells
If WorksheeyFunction.Substitute (cell.Value, " ", "") = textToSearch Then '<--|remove every space occurrence from cell value and compare it to your "nospace" searched value
MyMatch = cell.Column - rng.Columns(1).Column + 1
Exit For
End If
Next cell
End If
End With
使用方法如下:
Dim StateProvince As Long
StateProvince = MyMatch("State/Province", hr.Sheets("Open").Rows(1)) '<--| pass an "unspaced" string to search
If StateProvince > 0 Then
' code for handling found StateProvince
Else
' code for handling NOT found StateProvince
End If