将只有 space 值的单元格替换为 VBA

Substituting cells with only a space value with VBA

原始数据集是手填的。这会导致用户将 space 添加到原本空白的单元格中。寻找用空白单元格替换此单元格的方法。

一直在尝试 TRIM 和 VBA 的公式形式,但这些似乎没有切中要害。也一直在尝试用任何东西替换 spaces,但这也会删除文本值中的 spaces。

Sub CleanKlussen()
    Worksheets("WorkSheetX").Select
    Range("AC2").Select
        Range(Selection, Selection.End(xlToLeft)).Select
        Range(Selection, Selection.End(xlToLeft)).Select
        Range(Selection, Selection.End(xlToLeft)).Select
        Range(Selection, Selection.End(xlToLeft)).Select
        Range(Selection, Selection.End(xlToLeft)).Select
        Range(Selection, Selection.End(xlToLeft)).Select
        Range(Selection, Selection.End(xlDown)).Select
        Range(Selection, Selection.End(xlDown)).Select
        Range(Selection, Selection.End(xlDown)).Select
        For Each cell In ActiveSheet.UsedRange
            cell.Value = Trim(cell)
        Next cell
End Sub

对于选定 sheet 上的选定范围,我希望所有单元格只包含 1 或 2 spaces(没有任何其他值)被任何东西取代(创建一个空单元格).

Dim c As Range
For Each c In Selection
    If Len(WorksheetFunction.Trim(c.Value2)) = 0 Then c.ClearContents
Next c

或另一种方法,循环执行以下内容,直到找不到任何内容

    dim r as excel.range

    set r = Range("A1:C3").Find(What:=" ", After:=Range("a1"), LookIn:=xlFormulas, LookAt _
            :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
            False, SearchFormat:=False)
   r.clearcontents

一定不要trim数值,否则会被转成字符串。

For Each cell In ActiveSheet.UsedRange
    Dim v As Variant
    v = cell.Value2
    If Not IsNumeric(v) Then
        v = Trim(v)
        If v = "" Then
            cell.ClearContents
        Else
            cell.Value2 = v
        End If
    End If
Next cell

N.B。摆脱代码中所有这些无用的 Select 语句。