Monday, July 15, 2013

Excel Macro VBA remove extra space

Sub TrimColumn()
'Purpose: Remove extra empty space of data in each cell for the whole column
'Example: "abc      " -> "abc"
Dim i As Double
Dim NoOfRows As Double
Dim ColumnNo As Integer
Dim DataRange As Variant
Dim myString As String

NoOfRows = ActiveSheet.UsedRange.Rows.Count
ColumnNo = ActiveCell.Column
DataRange = Range(Cells(1, ColumnNo), Cells(NoOfRows, ColumnNo))

If IsEmpty(DataRange) = True Then
    Exit Sub
End If

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .DisplayStatusBar = False
End With

For i = 1 To NoOfRows
    myString = DataRange(i, 1)
    myString = Trim(myString)
    DataRange(i, 1) = myString
Next

Range(Cells(1, ColumnNo), Cells(NoOfRows, ColumnNo)) = DataRange

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
    .DisplayStatusBar = True
End With

End Sub

No comments:

Post a Comment