[英]Issues stripping special characters from text in VBA
我有一個 Excel 文件,它從 csv 中提取數據,對其進行一些操作,然后將其保存為一系列文本文件。
源數據中有一些特殊字符會出錯,所以我添加了這個來去除它們
Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?,â,€,™"
Function ReplaceSpecialCharacters(myString As String) As String
Dim newString As String
Dim char As Variant
newString = myString
For Each char In Split(SpecialCharacters, ",")
newString = Replace(newString, char, "")
Next
ReplaceSpecialCharacters = newString
End Function
問題是這並沒有抓住所有的人。 當我嘗試處理以下文本時,它會跳過上面的代碼並導致 Excel 出錯。
Hero’s Village
我認為問題在於特殊字符未被 Excel 本身識別。 我只能通過將文本從 Excel 復制出來並將其粘貼到不同的 IDE 中來使文本看起來像上面那樣。在 Excel 中顯示為:
基於此站點,它似乎在顯示'
字符時出現問題,但是如果它甚至無法在 VBA 本身中正確讀取它,我該如何修復/過濾掉它?
Option Explicit
dim mystring as String
dim regex as new RegExp
Private Function rgclean(ByVal mystring As String) As String
'function that find and replace string if contains regex pattern
'returns str
With regex
.Global = True
.Pattern = "[^ \w]" 'regex pattern will ignore spaces, word and number characters...
End With
rgclean = regex.Replace(mystring, "") '.. and replaces everything else with ""
End Function
嘗試使用正則表達式。
確保啟用正則表達式:工具 > 參考 > 復選框:“Microsoft VBScript 正則表達式 5.5”
將“mystring”字符串變量傳遞到 function (rgclean)。 function 將檢查任何非空格、單詞 [A-Za-z] 或數字 [0-9] 的內容,將它們替換為“”,然后返回字符串。
function 幾乎會刪除字符串中的所有符號。 不會排除任何數字、空格或單詞。
這是相反的方法。 刪除不包含在這組 62 中的所有字符:
ABCDEFGHIJKLMNOPQESTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
代碼:
Const ValidCharacters As String = "ABCDEFGHIJKLMNOPQESTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Function ReplaceSpecialCharacters(myString As String) As String
Dim newString As String, L As Long, i As Long
Dim char As Variant
newString = myString
L = Len(newString)
For i = 1 To L
char = Mid(newString, i, 1)
If InStr(ValidCharacters, char) = 0 Then
newString = Replace(newString, char, "@")
End If
Next i
ReplaceSpecialCharacters = Replace(newString, "@", "")
End Function
筆記:
如果要保留字符,還可以將字符添加到字符串ValidCharacters
中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.