使用excel VBA修剪非空行

时间:2018-02-15 05:51:24

标签: excel vba excel-vba

我使用下面的代码来修剪A列中的数据,但它给出了我定义的错误。有人可以帮我这个。

Sub RemoveLeadingSpace()

Dim spem As Workbook
Dim calc As Worksheet

Set spem = Excel.Workbooks("Sw.xlsm")
Set calc = spem.Worksheets("calc")

spem.Worksheets("calc").Activate

Dim LR As Long, i As Long
LR = Range("A" & Rows.count).End(xlUp).row
For i = 1 To LR
    With calc.Range("A" & i)
        calc.Range("A" & i).Value = Trim(calc.Range("A" & i).Value)
    End With
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

另一个解决方法是检查相关单元格是否包含错误,如下所示,也不需要spem.Worksheets("calc").Activate行。

Sub RemoveLeadingSpace()
Dim spem As Workbook: Set spem = Excel.Workbooks("Sw.xlsm")
Dim calc As Worksheet: Set calc = spem.Worksheets("calc")
'above declare and set you workbook and worksheet
Dim LR As Long, i As Long

LR = Range("A" & Rows.Count).End(xlUp).Row
'get the last row with data

For i = 1 To LR 'loop from row 1 to last
    If Not IsError(calc.Range("A" & i).Value) Then 'check if cell contains error
        calc.Range("A" & i).Value = Trim(calc.Range("A" & i).Value) 
        'if no error, then trim
    End If
Next i

End Sub