2016-06-28 81 views
1

我正在搜索包含特定文本的列標題的HR表單。此文本可以每週更改,例如,名爲「州/省​​」的列可能在一週內沒有空格,但下一週可能是「州/省​​」(請注意字詞之間的空格)。vba WorksheetFunction.Match搜索多個值

我目前使用下面的代碼,以查找一個條件

StateProvince = WorksheetFunction.Match("State/Province", hr.Sheets("Open").Rows(1), 0) 

這工作得很好,但我期待加入到這一點,以便它看起來包含空格,如果這是第二個例子列標題的情況。有什麼建議麼?

+0

與空格相同 –

+0

如果找不到第一個條件,我會得到一個錯誤,我試圖使代碼儘可能動態 –

+0

用錯誤捕獲它們,在VBA中使用工作表函數會給出一個呃ror,所以如果第一次使用第二次,如果沒有,請跳過第二次。或使用通配符* –

回答

2

用途:

StateProvince = WorksheetFunction.Match("State*/*Province", hr.Sheets("Open").Rows(1), 0) 

這個答案是具體到你的問題。如果你想要更通用的解決方案,你必須提供其他例子。

+0

*做什麼?我是否可以在單詞的開頭或結尾放置它,以便在每個單詞之前或之後照顧可能的空間? –

+0

@AaronC - '*'是一個通配符,可以代替任意數量的字符。例如,「Tr * y」與「托盤」,「特洛伊」和「手推車」相匹配。有關詳細信息,請參見[本](https://www.deskbright.com/excel/excel-wildcard/)。 – Mrig

+0

@AaronC - 在你的例子中'State */* Province'甚至可以匹配'States/Province','State/New Province'等字符串。 – Mrig

0

由於空間的不可預知的外觀,你最好忽略它們altoghether通過自定義功能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