vba 如果打开工作簿,请关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28163552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:58:37  来源:igfitidea点击:

Close a Workbook if opened

excelvba

提问by DPA

I would like an error handler to handle closing an Excel workbook that is not open.

我想要一个错误处理程序来处理关闭未打开的 Excel 工作簿。

I tried below code.

我试过下面的代码。

If Workbooks("Combo.xlsx").IsOpen Then 
     Workbooks("Combo.xlsx").Close SaveChanges:=False 
Else: Resume Next 
MsgBox "Error: (" & Err.Number & ") " & Err.Description, vbCritical 
End If 

This gives me an error message:

这给了我一条错误消息:

Run time Error: 9 Subscript Out of Range.

运行时错误:9 下标超出范围。

回答by Tim Williams

All you really need is

你真正需要的是

On Error Resume Next
Workbooks("Combo.xlsx").Close SaveChanges:=False
On Error Goto 0

You can ignore the error if there is no workbook open with that name.

如果没有使用该名称打开的工作簿,您可以忽略该错误。

回答by Petter

I had the same problem that the On Error Resume Next didn't seem to work for this. My settings are only to break on unhandled errors so I can't understand why it keeps breaking when trying to close.

我遇到了同样的问题,即 On Error Resume Next 似乎对此不起作用。我的设置只是在未处理的错误时中断,所以我不明白为什么它在尝试关闭时总是中断。

Anyway, I made this simple workaround subroutine to call when closing the workbook:

无论如何,我在关闭工作簿时调用了这个简单的解决方法子例程:

Private Sub closeWorkbookIfOpen(wb As Workbook)
    On Error GoTo NotOpen

    wb.Close

NotOpen:
End Sub

Not sure why the Resume Next doesn't work, but this seems to do the trick!

不知道为什么 Resume Next 不起作用,但这似乎可以解决问题!