如何执行不显示为宏的子?

时间:2017-11-08 11:58:55

标签: excel vba excel-vba

我在此网站上找到了一段很棒的代码,我想将其添加到我的工作簿中:

Trim all cells within a workbook(VBA)

代码是:

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

我已尝试将其复制并粘贴到Excel模块中,但无法弄清楚如何执行它。我真的真的新的,所以如果这是一个愚蠢的问题,我提前道歉。我已经搜索过为什么Sub不会显示为宏,而我发现的最佳答案是因为它包含变量?

我意识到原始海报试图修改加载项;我希望有一种方法可以在工作簿上调用它。

谢谢!

1 个答案:

答案 0 :(得分:3)

子例程期望将工作簿作为参数Sub DoTrim(Wb As Workbook),因此您无法从宏窗口运行它

如果Excel模块位于您要修剪的同一工作簿中,则可以删除该参数并使用ThisWorkbook对象来循环遍历工作簿中的工作表,如下所示:

Sub DoTrim()
    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 ThisWorkbook.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