[英]VBA: How to identify cells that have spaces at the beginning or end of the cell value

I have a dataset that is 80 columns by 200,000 rows. This data contains cell values that have beginning or trailing spaces. I need to identify which cells have those spaces.


If the dataset were smaller I could easily write a couple of for loops to check each cell for spaces. However, considering the size of the data, checking each cell would slow excel down (if not crash it). I anticipate that auto filter would end the same way.


Is there any way to efficiently check the dataset for spaces at the beginning or end of a cell value, without going cell by cell via loop


3 个解决方案



Private Sub this()
    Dim i As Long, j As Long
    Dim sh As Worksheet
    Dim sheetArr As Variant
    Set sh = ThisWorkbook.Sheets("Sheet1")
    sheetArr = sh.UsedRange
    rowC = sh.UsedRange.Rows.Count
    colC = sh.UsedRange.Columns.Count
    For i = 1 To rowC
        For j = 1 To colC
            If Left(sheetArr(i, j), 1) = " " Then
                sh.Cells(i, j).Interior.ColorIndex = 37
            End If
            If Right(sheetArr(i, j), 1) = " " Then
                sh.Cells(i, j).Interior.ColorIndex = 37
            End If
        Next j
    Next i
End Sub

I tested this on a 1 million row sheet and was done within 5 seconds. This should be good enough.


enter image description here



1) Select all cells you want to use


2) Click on Home -> Condition formatting button -> New Rule

2)單擊主頁 - >條件格式按鈕 - >新規則

3) Scroll down to "Use a formula to determine which cells to format"


4) Assuming your current cell is A1, type in the followiing


=OR((RIGHT(A1,1)=" "),(LEFT(A1,1)=" "))

5) Press format button, click on "Fill" an choose a color for fill


6) Press "ok", "ok".


The cells should be highlighted now




A loop might be slow if you query the workbook cell by cell. Instead, a loop querying a variant array will be much much faster:


Dim i as long
Dim j as long
Dim a() as Variant
a = yourrange.value
for i = lbound(a,1) to ubound(a,1)
  for j = lbound(a,2) to ubound(a,2)
    if left(a(i,j),1) = " " or right(a(i,j),1) = " " then
     'beginning or ending with " "
    end if
  next j
next i

Another option would be to copy/paste the data to notepad++ for example and then use the extended search function with "\t " and " \t" as well as "\r\n " and " \r\n" in order to find " " next to tabs and breaks which separat columns and rows respectively

另一個選擇是將數據復制/粘貼到記事本++,然后使用擴展搜索功能“\ t”和“\ t”以及“\ r \ n”和“\ r \ n”以便在標簽和分隔符旁邊找到“”,分別分隔列和行



粤ICP备14056181号  © 2014-2021 ITdaan.com