Trim all cells within a workbook(VBA)

吃可爱长大的小学妹 提交于 2019-12-06 01:40:59

Untested

Is this what you are trying?

Sub DoTrim(Wb As Workbook)
    Dim aCell As Range
    Dim wsh As Worksheet

    '~~> If you are using it in an Add-In, it is advisable 
    '~~> to keep the user posted :)
    Application.StatusBar = "Processing Worksheets... Please do not disturb..."
    DoEvents

    Application.ScreenUpdating = False

    For Each wsh In Wb.Worksheets
        With wsh
            Application.StatusBar = "Processing Worksheet " & _
                                    .Name & ". Please do not disturb..."
            DoEvents

            For Each aCell In .UsedRange
                If Not aCell.Value = "" And aCell.HasFormula = False Then
                    With aCell
                        .Value = Replace(.Value, Chr(160), "")
                        .Value = Application.WorksheetFunction.Clean(.Value)
                        .Value = Trim(.Value)
                    End With
                End If
            Next aCell
        End With
    Next wsh

    Application.ScreenUpdating = True
    Application.StatusBar = "Done"
End Sub

I agree with Siddarth:

For Each cell In ActiveSheet.UsedRange

Should be:

For Each cell In wsh.UsedRange

I would have thought you should be able to remove with 'With wsh.UsedRange' statement around the loop as well.

As you are passing in a WorkBook reference, perhaps you should consider changin your outer For loop from:

For Each wsh In Worksheets

to:

For Each wsh In Wb.Worksheets
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!