函数“openfile”返回工作簿结束运行时错误“91”

我想通过下面的函数打开并引用一个工作簿。 只有函数产生运行时错误“91”:对象variables或块variables在跳回主代码之前未设置。 当我把精确的代码(只是不作为函数)到我的主代码,它完美的作品。 但我不想在我的主代码中拥有完整的function,因为我认为这是不必要的,也是丑陋的。 也许有人可以帮助我使我的代码更好,更好理解! 已经谢谢你了!

这是我主要的相关部分:

Sub main_sub() Dim WBtest As Workbook Dim WBpath As String WBpath = ThisWorkbook.Sheets("Control").Range("A6").Value 'read path WBtest = openfile(WBpath) 'I call my function here End Sub 

这是产生错误的函数该函数应该返回(新)打开的工作簿

 Public Function openfile(path As String) As Workbook 'path is fullpath Dim wb As Workbook Dim alreadyopen As Boolean For Each wb In Workbooks 'loop over all Workbooks If wb.FullName = path Then 'check if file is already open alreadyopen = True Set openfile = wb End If Next wb If alreadyopen = False Then 'file not yet opened --> open it Set openfile = Workbooks.Open(path) End If 'MsgBox openfile.name 'this returns the right name End Function 

当我把它写在我的主要子工程中时(但是很丑,所以我不希望它在那里)。

 Sub main_sub() Dim WBtest As Workbook Dim WBpath As String Dim wb As Workbook 'for loop Dim alreadyopen As Boolean WBpath = ThisWorkbook.Sheets("Control").Range("A6").Value 'read path For Each wb In Workbooks 'loop over all Workbooks If wb.FullName = WBpath Then alreadyopen = True Set WBtest = wb End If Next wb If alreadyopen = False Then 'file not yet opened --> open it Set WBtest = Workbooks.Open(WBpath) End If End Sub 

后来在我的代码中有一个类似的问题,我想要一个函数返回一个工作簿。 所以这似乎是问题所在。 函数如何返回工作簿? 我发现类似的functionreturnins工作表。 那些工作。 为什么不使用工作簿?

非常感谢你的帮助!

两种方法之间的不同之处在于,第一个方法是忘记Set位。 因此,解决scheme:

 Set WBtest = openfile(WBpath) 'I call my function here