【发布时间】:2020-04-06 12:16:10
【问题描述】:
这似乎是一个简单的功能,解决方案应该是直截了当的,但我找不到问题。
我有一个在子程序中调用的函数,它检查文件是否打开,如果没有打开它。
该函数运行完美,但是当它返回到调用它的主 sub 时,变量(True 或 False)失去了它的值,我收到错误 9: subscript out of range 在Set wb = Workbooks(MasterFileF) 行在主子中。
Function wbOpen(wbName As String) As Boolean
Dim wbO As Workbook
On Error Resume Next
Set wbO = Workbooks(wbName)
wbOpen = Not wbO Is Nothing
Set wbO = Nothing
End Function
Sub Macro5()
Dim wb As Workbook
Dim path As String
Dim MasterFile As String
Dim MasterFileF As String
Application.ScreenUpdating = False
'Get folder path
path = GetFolder()
If path = "" Then
MsgBox "No folder selected. Please start macro again and select a folder"
Exit Sub
Else
End If
MasterFile = Dir(path & "\*Master data*.xls*")
MasterFileF = path & "\" & MasterFile
'Check if workbook open if not open it
If wbOpen(MasterFile) = True Then
Set wb = Workbooks(MasterFileF)
Else
Set wb = Workbooks.Open(MasterFileF)
End If
函数变量的值在返回主子时丢失,我哪里出错了?
【问题讨论】:
-
您是否尝试过使用
F8单步执行您的代码? -
您也在使用
On Error Resume Next,但请重置它。使用On Error Goto 0来做到这一点。另外,我不会使用这种方法,我会遍历Application.Workbooks集合中的Workbooks来查找工作簿。 -
这就是我当前运行代码以查看问题所在的方式。我使用监视窗口查看问题出在哪里。一切都很好,直到它返回到主子,然后
wbOpen应该是 True 或 False空了 -
好的,我想我知道出了什么问题,现在正忙于解决方案。
标签: excel vba function variables boolean