退出所有工作簿的VBA Excel宏以无限循环结束
我想写一个宏,循环遍历所有excel工作簿(在多个实例中),打印所有工作簿中的活动工作表,并关闭所有excel实例 代码如下:退出所有工作簿的VBA Excel宏以无限循环结束,excel,vba,Excel,Vba,我想写一个宏,循环遍历所有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 I
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"
问题是,只有一个应用程序退出,然后宏在无限循环中结束。为什么?我尝试了几种方法,总是以无限循环结束
非常感谢你的想法 您完全关闭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
子测试()
Dim-xl作为Excel.Application
Set xl=GetObject(,“Excel.Application”)
如果xl不算什么,那么
MsgBox“无法设置xl”
出口接头
如果结束
将wb设置为Excel.工作簿
Dim循环计数为整数
循环计数=0
直到xl什么都不是
loopCount=loopCount+1
对于xl.工作簿中的每个wb
wb.ActiveSheet.PrintOut
wb.Saved=True
'关闭除包含宏的工作簿外的所有工作簿
如果是(wb.Name ThisWorkbook.Name),则
wb.关闭
'如果除包含宏的工作簿外的所有工作簿都已关闭,则它将终止
ElseIf(Workbooks.Count=1)则
转到终点
如果结束
下一个
如果loopCount>30,则
MsgBox“无限循环”
出口接头
如果结束
Set xl=GetObject(,“Excel.Application”)
环
'由于if(false),此部件只能通过GoTo访问
如果(假)那么
完:
'在此,您还可以关闭包含宏的工作簿
MsgBox“已成功结束”
如果结束
端接头
不幸的是,此解决方案无法解决多个excel实例运行的问题。测试情况:3个excel实例,每个实例有一个工作簿。结果:宏立即结束,因为它的实例中只有一个工作簿。对不起,您是对的。我无意中读到“…工作簿(在多个实例中)和…”。不幸的是,对于多重输入问题,我没有一个快速的答案……嗨,请原谅我回答晚了。我找不到在其他excel实例中操作工作表的方法。恐怕我不能帮你解决这个特殊的问题。