使用(VBA)第二次打开同一文件时,如果它已经处于打开状态,则关闭 Excel 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9445396/
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
Closing Excel file if it is already in open status when opening the same file second time using (VBA)
提问by user1222679
回答by Andrew
Check if it is open, if not, close it using close method.
检查它是否打开,如果没有,使用 close 方法关闭它。
The following code was sourced from this VBAXpress Article
以下代码来自这篇VBAXpress 文章
Function IsFileOpen(FileName As String)
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error Goto 0
Select Case iErr
Case 0: IsFileOpen = False
Case 70: IsFileOpen = True
Case Else: Error iErr
End Select
End Function
Sub test()
If Not IsFileOpen("C:\MyTest\volker2.xls") Then
Workbooks.Open "C:\MyTest\volker2.xls"
End If
End Sub
If you just want to close a workbook without the user being prompted for any confirmations about saving the workbook you can simply do this :
如果您只想关闭工作簿而不提示用户确认保存工作簿,您可以简单地执行以下操作:
ActiveWorkbook.Close False
' closes the active workbook without saving any changes
' 关闭活动工作簿而不保存任何更改
ActiveWorkbook.Close True
' closes the active workbook and saves any changes
' 关闭活动工作簿并保存所有更改
ActiveWorkbook.Close
' closes the active workbook and lets the user decide if changes are to be saved or not
' 关闭活动工作簿并让用户决定是否保存更改
Workbooks("BOOK1.XLS").Close SaveChanges:=False