我有以下代码,应检查文件是否打开。如果文件已打开,则它什么都不做,但如果文件未打开,则应显示一条消息,指出文件未打开,然后退出子程序。
但是,无论文件是否打开,它始终会退出。
Sub Update_Folder()
Dim str As String
Dim openPos As Integer
Dim closePos As Integer
Dim midBit As String
'Creates file string name
str = Range("H6").Value
openPos = InStr(str, "[")
closePos = InStr(str, "]")
midBit = Mid(str, openPos + 1, closePos - openPos - 1)
If Range("B2").Value = "Yes" Or Range("B4").Value = "Yes" Or Range("B5").Value = "Yes" Or Range("B6").Value = "Yes" Or Range("B9").Value = "Yes" Or Range("B12").Value = "Yes" Or Range("B13").Value = "Yes" Then
On Error Resume Next
Set WB = Workbooks(midBit)
If Err Then MsgBox ("Please open the following file(s): " & str)
'Exit Sub
On Error GoTo 0
End If
Call Folder_Creation
END SUB
检查文件是否打开的正确语法是什么?如果没有打开文件,则什么也不做,请显示msgbox
并退出sub?单元格H6
是C:\Users\User1\Documents\[TestFile.xlsx]
。
我尝试了以下链接中的解决方案,但 Detect whether Excel workbook is already open
它对我不起作用。可能是因为我基于单元格中的文件路径设置了路径?运行文件时出现文件未找到错误。 debug
屏幕将我带到Case Else: Error ErrNo
行。
更新:
以下代码对我有用。我必须更改Error GoTo
语法,然后将error handler
移动到脚本的末尾。因此,如果发生错误,它将跳至脚本底部
Sub Update_Folder()
Dim str As String
Dim openPos As Integer
Dim closePos As Integer
Dim midBit As String
'Creates file string name
str = Range("H6").Value
openPos = InStr(str, "[")
closePos = InStr(str, "]")
midBit = Mid(str, openPos + 1, closePos - openPos - 1)
If Range("B2").Value = "Yes" Or Range("B4").Value = "Yes" Or Range("B5").Value = "Yes" Or Range("B6").Value = "Yes" Or Range("B9").Value = "Yes" Or Range("B12").Value = "Yes" Or Range("B13").Value = "Yes" Then
On Error goto ErrorHandler1:
Set WB = Workbooks(midBit)
If Err Then MsgBox ("Please open the following file(s): " & str)
'Exit Sub
Call Folder_Creation
ErrorHandler1:
MsgBox ("Please open the following file(s): " & str)
Exit Sub
END SUB
答案 0 :(得分:0)
也许会有所帮助:
用于检查文件是否已打开的宏代码
https://support.microsoft.com/en-us/help/291295/macro-code-to-check-whether-a-file-is-already-open
按照上面的链接中的说明进行操作。如下所示:在Excel中,按Alt + F11调出VBA。单击插入>模块。复制并粘贴代码。返回Excel,如下图所示设置单元格。这是应该设置您的单元格的方式: