excel - 突出显示值前后有空格的单元格

标签 excel vba

我创建了一个小宏,用于突出显示名称中包含多个空格的单元格。现在我注意到在名称之前和之后也有带有空格的值。如何编辑我当前的代码,使其突出显示单元格,例如“Word word”或“Word word”或“Word word”

所以唯一能通过验证的就是当一切都像“Word word”一样正确编写的情况下

这是我当前的代码:

Sub MarkMoreThanOneSpace()

Dim Cell
Dim rng As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

    Set rng = ThisWorkbook.Worksheets("Main").Range("A2:L" & ThisWorkbook.Worksheets("Main").Range("A2").End(xlDown).Row)

    For Each Cell In rng
    If WorksheetFunction.CountIf(Cell, "*  *") > 0 Then

        Cell.Interior.ColorIndex = 6

    Exit Sub
    End

    End If

    Next Cell

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

最佳答案

你可以使用 WorksheetFunction.Trim()功能

循环遍历具有值的单元格只是为了缩短时间

不要在第一次发现时退出,否则你会错过所有其他人

不要使用End !

Sub MarkMoreThanOneSpace()

    Dim cell As Range
    Dim rng As Range

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set rng = ThisWorkbook.Worksheets("Main").Range("A2:L" & ThisWorkbook.Worksheets("Main").Range("A2").End(xlDown).Row)

    For Each cell In rng.SpecialCells(xlCellTypeConstants)
        If WorksheetFunction.Trim(cell.Value) <> cell.Value Then cell.Interior.ColorIndex = 6
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

关于excel - 突出显示值前后有空格的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780092/

相关文章:

c# - 导出数据表时如何去除export to excel警告

excel - 编译错误: END IF Without Block IF (Persistent Error) [closed]

excel - 根据唯一值获取最大值

vba - 删除超链接性能

excel - 获取 PivotItem 的源范围

Excel VBA 不会粘贴前导零

vba - 如何使Excel VBA变量可用于多个宏?

excel - 公式数组问题

excel - 使用 SendKeys 选择单元格

vba - 如何确定包含各种形状的工作表上的形状类型?