我有以下代码,应该删除所有不可打印的字符并修剪单元格中的所有空格,但由于某种原因,它不会在所有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
答案 0 :(得分:3)
请尝试以下代码:
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
的任何引用,并且仅适用于用户选择的单元格。如果需要处理整个列,则可以由用户选择,但Intersect
将确保仅处理使用过的单元格。
在.Cells
中加入For Each CellChecker In rngremovespace.Cells
可确保所选的任何不连续的单元格范围不会导致For Each
处理每个“区域”,而是分别处理每个单元格
答案 1 :(得分:0)
嘿,要删除所有不可打印的字符以及Trim,请在代码中使用此命令行,
cell.Value = Application.WorksheetFunction.Clean(cell.Value)
答案 2 :(得分:0)
您对待治疗范围的定义似乎不准确。试试这种方式: -
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