3

I am trying to find any cells with just spaces in. When I run this though it finds cells that are blanks too. Is there anyway to just find cells with spaces?

For i = 1 to lastRow
If len(trim(this workbook.sheets("data").range("a" & i)) = 0 then
Msgbox("a" & i " contains only space")
End if
Next i
BCLtd
  • 1,459
  • 2
  • 18
  • 45

6 Answers6

3

Plase, try:

Sub testFindSpaces()
Dim wsD as Worksheet, i As Long, x As String, lastRow As Long

 Set wsD = ThisWorkbook.Sheets("data")
 lastRow = wsD.Range("A" & wsD.rows.count).End(xlUp).row
 For i = 1 To lastRow
    x = wsD.Range("a" & i).Value
    If UBound(Split(x, " ")) = Len(x) Then
        MsgBox "a" & i & " contains only space"
    End If
Next i
End Sub
T.M.
  • 9,436
  • 3
  • 33
  • 57
FaneDuru
  • 38,298
  • 4
  • 19
  • 27
  • 1
    An efficient & elegant solution +:) - btw *would fully qualify `lastRow`, too*. @FaneDuru – T.M. Aug 23 '21 at 16:28
  • @T.M. Thanks! Yah, that variable did not make part from the question. I tried suggesting that the variables declaration is important, and I tried giving values to all of them... I will adapt it in a way to everything be fully qualified... – FaneDuru Aug 23 '21 at 18:20
  • @T.M. Splitting each cell's contents into an array (a heap object that must be allocated), one element per character in the worst case, for the purpose of checking for spaces is certainly the opposite of efficient, and arguably the opposite of elegant. – GSerg Aug 23 '21 at 18:41
  • @GSerg Appreciating your comment, I agree with the criticism regarding the efficiency of split actions for the individual cell values. In contrast, I find the reduction of the criteria checks to a single one elegant and, in this respect, also efficient. In any case, showing alternatives finally contributes to the development of better solutions. – T.M. Aug 23 '21 at 19:05
  • worked like a charm, sorry for the delay in marking this – BCLtd Aug 29 '21 at 20:29
3

Just exclude blanks by testing for Len(ThisWorkbook.Worksheets("data").Range("A" & i)) <> 0 too.

For i = 1 to lastRow
    Dim Untrimmed As String
    Untrimmed = ThisWorkbook.Worksheets("data").Range("A" & i).Value

    If Len(Trim(Untrimmed) = 0 AND Len(Untrimmed) <> 0 then
        Msgbox "a" & i & " contains only space"
    End if
Next i

Alternativeley use ThisWorkbook.Worksheets("data").Range("A" & i).Value <> vbNullString to exclude blanks

For i = 1 to lastRow
    Dim Untrimmed As String
    Untrimmed = ThisWorkbook.Worksheets("data").Range("A" & i).Value

    If Len(Trim(Untrimmed) = 0 AND Untrimmed <> vbNullString then
        Msgbox "a" & i & " contains only space"
    End if
Next i
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
3

Just to add alternatives:

With ThisWorkbook.Sheets("data").Range("A" & i)
    If .Value Like "?*" And Not .Value Like "*[! ]*" Then
        MsgBox ("A" & i & " contains only space")
    End If
End With

You may also just create a new regex-object and use pattern ^ +$ to validate the input.


If you don't want to loop the entire range but beforehand would like to exclude the empty cells you could (depending on your data) use xlCellTypeConstants or the numeric equivalent 2 when you decide to use SpecialCells() method and loop the returned cells instead:

Dim rng As Range, cl As Range

Set rng = ThisWorkbook.Worksheets("Data").Range("A:A").SpecialCells(2)
For Each cl In rng
    If Not cl.Value Like "*[! ]*" Then
        MsgBox ("A" & cl.Row & " contains only spaces")
    End If
Next cl

You may also no longer need to find your last used row, but note that this may error out if no data at all is found in column A.


A last option I just thought about is just some concatenation before validation:

For i = 1 To lastRow
    If "|" & Trim(ThisWorkbook.Sheets("data").Range("A" & i).value & "|" = "| |" Then
        MsgBox ("A" & i & " contains only space")
    End If
Next
JvdV
  • 70,606
  • 8
  • 39
  • 70
3

Macro to get a string of address of cells containing only space using Evaluate VBA function

Edited code below - As suggested by @VBasic2008 and @T.M. in the comments below.

Option Explicit
Sub Cells_with_Space_Only()
Dim ws As Worksheet
Set ws = Sheets("Sheet2")
'Macro to get a string of address of cells containing only space
'https://stackoverflow.com/questions/68891170/finding-cells-with-only-spaces
Dim rngArr, rngStr As String, i As Long, rng As Range
rngArr = Evaluate("IFERROR(ADDRESS((ISBLANK(" & ws.UsedRange.Address(External:=True) & _
            ")=FALSE)*(" & ws.UsedRange.Address(External:=True) & _
            "=REPT("" "",LEN(" & ws.UsedRange.Address(External:=True) & _
            ")))*ROW(" & ws.UsedRange.Address(External:=True) & _
            "),COLUMN(" & ws.UsedRange.Address(External:=True) & ")),""**"")")
rngStr = ""

'If number of columns in usedrange are less then loop with
'For i = 1 To ActiveSheet.UsedRange.Columns.Count
For i = 1 To ws.UsedRange.Rows.Count
    'if looped with For i = 1 To ActiveSheet.UsedRange.Columns.Count
    'rngStr = Join(Filter(Application.Transpose(Application.Index(rngArr, 0, i)) _
                , "**", False, vbBinaryCompare), ",")
    
    rngStr = Join(Filter(Application.Index(rngArr, i, 0) _
                , "**", False, vbBinaryCompare), ",")
    If rngStr <> "" Then
        If rng Is Nothing Then
            Set rng = Range(rngStr)
        Else
            Set rng = Union(rng, Range(rngStr))
        End If
    End If
Next i

Debug.Print rng.Address

End Sub

The macro returns a string for the sample data in the image below -- $D$1,$A$2,$F$2,$B$3,$E$4,$A$6,$F$6,$E$7,$B$8,$D$9,$C$10,$F$10,$A$11,$D$13,$F$13,$E$14,$A$16,$E$16,$D$17,$F$17:$F$18

Array formula in the worksheet -

=IFERROR(ADDRESS((ISBLANK($A$1:$F$18)=FALSE)*($A$1:$F$18=REPT(" ",LEN($A$1:$F$18)))*ROW($A$1:$F$18),COLUMN($A$1:$F$18)),"**")

enter image description here

Naresh
  • 2,984
  • 2
  • 9
  • 15
  • 1
    That's a cool idea. Note that it only works for the `ActiveSheet` i.e. don't forget to previously activate the worksheet in the code. Also, note that the string you pass as the address to a range mustn't exceed the limit of 252 or so characters. – VBasic2008 Aug 23 '21 at 13:17
  • @VBasic2008, thanks .. Editing the answer. – Naresh Aug 23 '21 at 13:42
  • 1
    Friendly hint: to make the range reference waterproof within `Evaluate`, too it'll be necessary to include `External:=True` as argument to `.Address`, i.e. `Evaluate("IFERROR(ADDRESS((" & ws.UsedRange.Address(External:=True) & ...` or at least to prefix the address by a concrete sheet reference plus `"!"` @Naresh – T.M. Aug 23 '21 at 14:45
  • 1
    Thank you @T.M :) ... After testing the code on two sheets, I understood that. Yes, external=true worked. Editing the answer. Happy to learn. – Naresh Aug 23 '21 at 14:55
2

Clear Solo Spaces

  • Couldn't think of any reason for doing this other than for clearing the cells containing only spaces.
Option Explicit

Sub ClearSoloSpaces()
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Worksheets("Data")
    
    Dim srg As Range ' Source Range
    Set srg = ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp))
    
    Dim crg As Range ' Clear Range
    Dim cCell As Range ' Current Cell in Source Range
    Dim cString As String ' Current Cell's Value Converted to a String
    For Each cCell In srg.Cells
        cString = CStr(cCell.Value)
        If Len(cString) > 0 Then
            If Len(Trim(cString)) = 0 Then
                If crg Is Nothing Then
                    Set crg = cCell
                Else
                    Set crg = Union(crg, cCell)
                End If
            End If
        End If
    Next cCell
    
    If crg Is Nothing Then
        MsgBox "No cells containing only spaces found.", _
            vbInformation, "Clear Solo Spaces"
    Else
        Dim Msg As Long
        Msg = MsgBox("The cells in the rows '" _
            & Replace(crg.Address, "$A$", "") _
            & "' of column 'A' contain only spaces." & vbLf _
            & "Do you want to clear them?", _
            vbInformation + vbYesNo, "Clear Solo Spaces")
        If Msg = vbYes Then
            crg.Clear ' or crg.ClearContents ' to preserve formatting
        End If
    End If

End Sub
VBasic2008
  • 44,888
  • 5
  • 17
  • 28
0

Just for the sake of showing alternatives (@T.M.), please test the next one, too:

Private Sub testFindSpacesBis() 
 Dim wsD As Worksheet, i As Long, x As String, lastRow As Long

 Set wsD = ActiveSheet ' ThisWorkbook.Sheets("data")
 lastRow = wsD.Range("A" & wsD.rows.count).End(xlUp).row
 For i = 1 To lastRow
    x = wsD.Range("a" & i).Value
    If StrComp(x, space(Len(x)), vbBinaryCompare) = 0 Then
        MsgBox "a" & i & " contains only spaces"
    End If
 Next i
End Sub
FaneDuru
  • 38,298
  • 4
  • 19
  • 27