从VBA中的单元中删除ChrW和空间
我有下面的代码,应该删除所有不可打印的字符,并修剪单元格中的所有空间,但由于某些原因,它没有在所有selected
单元格上执行。
Sub removeSpace() Dim rngremovespace As Range Dim CellChecker As Range Set rngremovespace = Selection rngremovespace.Columns.Replace What:=Chr(160), Replacement:=Chr(32), _ LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False For Each CellChecker In rngremovespace.Columns CellChecker.Value = Application.Trim(CellChecker.Value) CellChecker.Value = Application.WorksheetFunction.Clean(CellChecker.Value) Next CellChecker Set rngremovespace = Nothing End Sub
试试下面的代码:
Sub removeSpace() Dim rngremovespace As Range Dim CellChecker As Range Set rngremovespace = Intersect(ActiveSheet.UsedRange, Selection) rngremovespace.Replace What:=Chr(160), _ Replacement:=Chr(32), _ LookAt:=xlPart, _ SearchOrder:=xlByColumns, _ MatchCase:=False For Each CellChecker In rngremovespace.Cells CellChecker.Value = Application.Trim(CellChecker.Value) CellChecker.Value = Application.Clean(CellChecker.Value) Next CellChecker Set rngremovespace = Nothing End Sub
上面的代码避免了对Columns
任何引用,只是对用户select的单元格起作用。 如果需要处理整个列,那么可以由用户select,但Intersect
将确保只处理已使用的单元格。
在For Each CellChecker In rngremovespace.Cells
包含For Each CellChecker In rngremovespace.Cells
确保所选的不连续单元格区域不会导致For Each
处理每个“区域”,而是分别处理每个单元格。
嘿删除所有不可打印的字符以及修剪请使用此命令行与您的代码,,
cell.Value = Application.WorksheetFunction.Clean(cell.Value)
您对待处理范围的定义似乎不够精确。 试试这个方法:
Sub removeSpace() Dim rngremovespace As Range Dim CellChecker As Range With Selection Set rngremovespace = Range(Columns(.Column), Columns(.Column + .Columns.Count)) End With rngremovespace.Replace What:=Chr(160), Replacement:=Chr(32), _ LookAt:=xlPart, SearchOrder:=xlByColumns, _ MatchCase:=False For Each CellChecker In rngremovespace CellChecker.Value = Application.Trim(CellChecker.Value) CellChecker.Value = Application.WorksheetFunction.Clean(CellChecker.Value) Next CellChecker Set rngremovespace = Nothing End Sub