Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TRIM function/remove spaces from cells using VBA

Tags:

excel

vba

I am using the code below to trim some "blank cells" that contain a space. The thing is it takes too much time, as is looping to every cell. What I want is to remove the spaces(the ones in the beginning and end, not middle), of all the cells.

Is there any easier way that I can apply all at once?

For a = 1 To ScenarioTableLastRow
    For f = 1 To ScenarioTableLastColumn

       If Cells(a, f) <> "" Then
            Cells(a, f) = Excel.Application.Trim(Cells(a, f))
       End If

    Next f
Next a
like image 262
Leandro Moreira Avatar asked Feb 09 '17 21:02

Leandro Moreira


People also ask

How do I remove spaces from a cell in Excel VBA?

To remove only the leading spaces from text in a cell we need to use the VBA LTrim function. The VBA LTrim function only removes the extra space at the start of the text in a cell. Therefore, any extra spaces at the end of the text or between words in a cell will remain.

How do I remove spaces between words in VBA?

Using trim (or trim$) in VBA will remove the leading and trailing spaces, which as mentioned is different from =TRIM in Excel. If you need to remove spaces (as mentioned below not necessarily all whitespace) from inside a string simply use WorksheetFunction. Trim . Save this answer.


2 Answers

You'll get much better performance copying the data into an array, and working on the array, then placing the data back into the range.

Also, don't use Excel.Application.Trim. That's Excel 95 syntax, and a late-bound call with unexpected error handling. VBA has a Trim function built-in - it's about 10 times faster and it provides Intellisense.

Sub test()

    'Assuming ScenarioTable is a range
    Dim ScenarioTable As Range
    Set ScenarioTable = Range("ScenarioTable")

    'I assume your range might have some formulas, so...
    'Get the formulas into an array
    Dim v As Variant
    v = ScenarioTable.Formula

    Dim a As Long
    Dim f As Long
    'Then loop over the array
    For a = LBound(v, 1) To UBound(v, 1)
        For f = LBound(v, 2) To UBound(v, 2)
            If Not IsEmpty(v(a, f)) Then
                v(a, f) = VBA.Trim(v(a, f))
            End If
        Next f
    Next a
    'Insert the results
    ScenarioTable.Formula = v
End Sub
like image 193
ThunderFrame Avatar answered Oct 20 '22 15:10

ThunderFrame


Do it on the whole range at once using the array version of Excel's Trim:

myRange.Value = Application.Trim(myRange.Value)

Using the only variables visible in your code, it would be:

With Range(Cells(1,1), Cells(ScenarioTableLastRow, ScenarioTableLastColumn))
     .Value = Application.Trim(.Value)
End With
like image 43
A.S.H Avatar answered Oct 20 '22 16:10

A.S.H