user9103716
user9103716

Reputation:

VBA delete spaces within a string

I want to be able to delete all of the spaces from a group of cells so that the cell contents result in just being a string of information that I want. I have come up with a code but it doesn't work and I can't figure out whether I have to use a replace function or not

My code is:

Sub Tester()

Dim SearchString As String
Dim cell As Range
Dim LastRowSource As Long
Dim ws1 As Worksheet

Set ws1 = ActiveWorkbook.ActiveSheet

SearchString = " " 'look for strings containing ( )

With ws1

    LastRowSource = .Cells.Find(" ", [B2], , , xlByRows, xlPrevious).Row

    For Each cell In .Range("B2:B" & LastRowSource)

            If InStr(cell.Value, SearchString) > 0 Then
                cell.Value = Replace(" ", "")
         End If
    Next cell
End Sub

Upvotes: 0

Views: 6814

Answers (3)

Rory
Rory

Reputation: 34045

You don't need to loop:

With ws1
    .Range("B2", .Cells(.rows.count, "B").End(xlUp)).Replace " ", vbnullstring, xlpart
End With

Upvotes: 0

Andy G
Andy G

Reputation: 19367

If you need to do this programmatically then, recording a Macro using the Replace dialog generates this code:

Sub Macro1()
    Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

Substitute your range for Selection. You do not need to iterate each cell.

Upvotes: 1

Vityata
Vityata

Reputation: 43585

Try like this:

LastRowSource = 10000. If it works, then the problem is the way you are setting the last row. Thus, add the LastRow() function to your code, it should work:

LastRowSource = LastRow ws1

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Function from here - https://www.rondebruin.nl/win/s9/win005.htm

Upvotes: 0

Related Questions