vba WorksheetFunction.Matchsearch多个值
我正在search包含特定文本的列标题的HR表。 这个文本可以每周更改,例如,一个名为“ 州/省 ”的列可能在一周内没有空格,但是下一个星期可能是“ 州/省 ”(注意单词之间的空格)。
我目前正在使用下面的代码,查找一个条件
StateProvince = WorksheetFunction.Match("State/Province", hr.Sheets("Open").Rows(1), 0)
这工作正常,但我期待添加到这个,以便它寻找包含空格的第二个例子,如果这是列标题的情况。 有什么build议么?
使用:
StateProvince = WorksheetFunction.Match("State*/*Province", hr.Sheets("Open").Rows(1), 0)
这个答案是针对你的问题的。 如果你想要更通用的解决scheme,你将不得不提供其他的例子。
由于空间的不可预知的外观,您最好通过自定义的MyMatch()
函数来忽略它们,方法是传递“ MyMatch()
”string,如下所示:
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