我创建了一个小宏,用于突出显示名称中包含多个空格的单元格。现在我注意到在名称之前和之后也有带有空格的值。如何编辑我当前的代码,使其突出显示单元格,例如“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/