2016-09-15 66 views
1

在Excel 2010中使用宏時,我試圖用空格替換所有「無效」字符(由命名區域定義)。在Excel 2010 vba宏中替換通配符(?和*)

Dim sanitisedString As String 
    sanitisedString = Application.WorksheetFunction.Clean(uncleanString) 
    Dim validCharacters As Range 
    Set validCharacters = ActiveWorkbook.Names("ValidCharacters").RefersToRange 
    Dim pos As Integer 
    For pos = 1 To Len(sanitisedString) 
     If WorksheetFunction.CountIf(validCharacters, Mid(sanitisedString, pos, 1)) = 0 Then 
      sanitisedString = WorksheetFunction.Replace(sanitisedString, pos, 1, " ") 
     End If 
    Next 

它適用於除*和?以外的所有字符,因爲CountIf將這些字符解釋爲通配符。

我試圖逃避在COUNTIF所有字符,使用:

If WorksheetFunction.CountIf(validCharacters, "~" & Mid(sanitisedString, pos, 1)) = 0 

但是這導致的所有字符替換,無論他們是否在名單與否。

然後我試圖做兩個獨立的替換命令,放置在使用循環 「〜*」 和 「〜?」 之後:

sanitisedString = WorksheetFunction.Substitute(sanitisedString, "~*", " ") 
sanitisedString = WorksheetFunction.Substitute(sanitisedString, "~?", " ") 

但*和?仍然通過。

我在做什麼錯?

回答

2

由於有onlyl兩個通配符擔心,你可以測試那些明確:

Dim character As String 
For pos = 1 To Len(sanitisedString) 
    character = Mid(sanitisedString, pos, 1) 
    If character = "*" Or character = "?" Then character = "~" & character 
    If WorksheetFunction.CountIf(validCharacters, character) = 0 Then 
     Mid$(sanitisedString, pos, 1) = " " 
    End If 
Next 
+0

好極了,謝謝:)我怎麼沒想到這一點...... – simonalexander2005