我正在尝试解析特定范围内所有Excel单元格中的左右空白,nbsp,\ n,\ t等。
我正在使用以下宏:
Sub TRIM_CELLS()
'Clean all conditional formating
Cells.FormatConditions.Delete
'improve performance
Application.ScreenUpdating = False
Dim all_cells_range As String
all_cells_range = "A1:A10"
'Trim all those cells
Range(all_cells_range).Select
For Each cell In Selection.Cells
cell.Value = Application.Substitute(Application.Substitute(CStr(cell.Value), vbLf, vbCr), vbCr, "")
cell = WorksheetFunction.Trim((Application.Clean(Replace(cell.Value, Chr(160), " "))))
Next cell
End Sub
“ Maria Tavares”之类的东西没有正确修剪。
答案 0 :(得分:1)
我使用一个函数来删除您定义的任何特殊字符。
Function RemoveSpecialCharacters(wks As Worksheet, strRange As String, var As Variant)
Dim rngAddress As Range, cell As Range, I&
'e.g strRange - "E2:E"
With wks
Set rngAddress = .Range(strRange & .Cells(Rows.count, "A").End(xlUp).row)
For I = LBound(var) To UBound(var)
For Each cell In rngAddress
cell = WorksheetFunction.Substitute(cell, var(I), " ")
Else
cell = WorksheetFunction.Substitute(cell, var(I), "")
Next cell
Next I
End With
End Function
您可以这样调用函数:
RemoveSpecialCharacters worksheetname, "A1:A", Array(Chr(9), Chr(10), Chr(13), Chr(39))
其中Chr(10)
是换行符,chr(9)
是制表符等。
请参见此link,以了解其他Chr
代码的含义。
更新:
尝试此操作从单元格中删除奇怪的“间谍”字符。
RemoveSpecialCharacters worksheetname, "A1:A", Array(Chr(160))
答案 1 :(得分:1)
@Nick:我尝试使用您的想法,我认为问题出在char本身...假设以下循环按预期工作,我将得到引起问题的char。
看看这张图片:
但是那个地方什么也没印出来。
Sub TRIM_CELLS()
'Clean all conditional formating
Cells.FormatConditions.Delete
'improve performance
Application.ScreenUpdating = False
Dim all_cells_range As String
all_cells_range = "A1:A2"
'Trim all those cells
Range(all_cells_range).Select
For Each cell In Selection.Cells
For I = 1 To 255
cell = WorksheetFunction.Substitute(cell, Chr(I), I)
Next I
Next cell
End Sub
答案 2 :(得分:0)
最终用那个“空格”代替了...不是一个很好的解决方案,但是解决了我的问题...只是想知道它是什么字符...
Sub TRIM_CELLS()
'Clean all conditional formating
Cells.FormatConditions.Delete
'improve performance
Application.ScreenUpdating = False
Dim all_cells_range As String
all_cells_range = "A1:A2"
Range(all_cells_range).Select
For Each cell In Selection.Cells
cell.Replace What:=" ", Replacement:=" ", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
cell.Value = Application.Substitute(Application.Substitute(CStr(cell.Value), vbLf, vbCr), vbCr, "")
cell.Value = WorksheetFunction.Trim(cell)
Next cell
end sub