由於空間的不可預知的外觀,你最好忽略它們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
與空格相同 –
如果找不到第一個條件,我會得到一個錯誤,我試圖使代碼儘可能動態 –
用錯誤捕獲它們,在VBA中使用工作表函數會給出一個呃ror,所以如果第一次使用第二次,如果沒有,請跳過第二次。或使用通配符* –