VBA Excel宏退出所有工作簿以无限循环结束

时间:2018-06-29 11:55:44

标签: excel-vba vba excel

我想编写一个宏来遍历所有excel工作簿(在多个实例中),并在所有工作簿中打印活动工作表并关闭所有excel实例。

代码如下:

Dim xl As Excel.Application
Set xl = GetObject(, "Excel.Application")
If xl Is Nothing Then
    msgbox "Unable to set xl"
    Exit Sub
End If

Dim wb As Excel.Workbook
Dim loopCount As Integer
loopCount = 0


Do Until xl Is Nothing
    loopCount = loopCount + 1

    For Each wb In xl.Workbooks
        wb.ActiveSheet.PrintOut
        wb.Saved = True
    Next

    xl.Quit

    If loopCount > 30 Then
        msgbox "Infinite loop"
        Exit Sub
    End If

    Set xl = GetObject(, "Excel.Application")

Loop

msgbox "Ended successfully"

问题是,只有一个应用程序终止,然后宏以无限循环结束。为什么?我尝试了几种热的方法来做,总是以无限循环结束。

非常感谢您的想法!

1 个答案:

答案 0 :(得分:1)

您完全关闭了excel,因此宏无法结束其工作。

尝试一下:

Sub test()

    Dim xl As Excel.Application
    Set xl = GetObject(, "Excel.Application")
    If xl Is Nothing Then
        MsgBox "Unable to set xl"
        Exit Sub
    End If

    Dim wb As Excel.Workbook
    Dim loopCount As Integer
    loopCount = 0


    Do Until xl Is Nothing
        loopCount = loopCount + 1

        For Each wb In xl.Workbooks
            wb.ActiveSheet.PrintOut
            wb.Saved = True
            ' closes all workbooks except the one which contains the macro
            If (wb.Name <> ThisWorkbook.Name) Then
                wb.Close
            ' if all workbooks except the one which contains the macro are closed, it junps to the end
            ElseIf (Workbooks.Count = 1) Then
                GoTo end
            End If
        Next



        If loopCount > 30 Then
            MsgBox "Infinite loop"
            Exit Sub
        End If

        Set xl = GetObject(, "Excel.Application")

    Loop



    ' due to if (false) this part is just reachable via GoTo
    If (False) Then
end:
    ' here you can also close the workbook which contains the macro
    MsgBox "Ended successfully"
    End If

End Sub