我有一个Excel 2013工作簿,其中包含从各种来源导入的工作表。
这些字符包含干净函数未考虑的地方的 Unicode 字符。
我发现了一个逐个细胞工作的功能,但是我想在一系列细胞上使用它,而不是必须将功能单独放在每个细胞中。
有人可以帮我转换这个功能吗?
谢谢
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
答案 0 :(得分:1)
这是我编写的子程序,经过测试工作。
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
答案 1 :(得分:1)
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