使用(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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:20:26  来源:igfitidea点击:

Closing Excel file if it is already in open status when opening the same file second time using (VBA)

excelvba

提问by user1222679

I have a command button which opens the excelfile.

我有一个打开excel文件的命令按钮。

But if the same file is opened for the second time it should first close it and then reopen it.

但是如果第二次打开同一个文件,它应该先关闭它,然后再重新打开它。

So i am looking for such code - I would be very thankful for this help.

所以我正在寻找这样的代码 - 我会非常感谢这个帮助。

回答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

回答by Karl Barker

Workbooks have a Closemethod.

工作簿有一个Close方法。

See here

这里