改善清除非打印和其他ASCII字符的function

我有一个Excel 2013工作簿,从各种来源导入工作表。

这些包含的Unicode字符遍布干净的function不占的地方。

我发现一个单元格逐个工作的函数,但是我想将它用在一系列单元格上,而不是必须将这个函数单独放在每个单元格中。

有人可以帮我转换这个function吗?

谢谢

Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String Dim X As Long, CodesToClean As Variant CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157) If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ") For X = LBound(CodesToClean) To UBound(CodesToClean) If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "") Next CleanTrim = WorksheetFunction.Trim(S) 'Call function == use CleanTrim just like it was a built-in Excel function. For example, =CleanTrim(B2) End Function 

这是我写的子程序,当testing工作。

 Sub CleanCells() Dim x As Long, CodesToClean As Variant CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157) Dim rng As Range Dim row As Range Dim cell As Range Set rng = Range("A1:A168") For Each row In rng.Rows For Each cell In row.Cells 'Do Something S = Replace(S, Chr(160), " ") For x = LBound(CodesToClean) To UBound(CodesToClean) If InStr(S, Chr(CodesToClean(x))) Then S = Replace(S, Chr(CodesToClean(x)), "") Next WorksheetFunction.Trim (S) Next cell Next row End Sub 

正则Regexp将更清洁。

作为下面的UDF (可以在数组中使用)

请参阅https://regex101.com/r/Hdv65h/1

 Function strClean(strIn As String) As String Dim objRegexp As Object Set objRegexp = CreateObject("vbscript.regexp") With objRegexp 'hex codes for 0-31, 127, 129, 141, 143, 144, 157 .Pattern = "[\x00-\x1F]|\x7F|\x7F|\x81|\x8D|\x8F|\x90|\x9D" .Global = True strClean = .Replace(strIn, vbNullString) End With End Function