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

时间:2013-07-29 08:10:28

标签: excel vba excel-vba

我想通过以下功能打开并引用工作簿。只有函数产生运行时错误'91':对象变量或者在跳回主代码之前没有设置块变量。 当我把确切的代码(只是不作为函数)放入我的主代码时,它完美地工作。 但是我不想在我的主代码中使用整个函数,因为我认为这是不必要的和丑陋的。 也许有人可以帮助我让我的代码更好,更易于理解! 谢谢你!

这是我主要子项的相关部分:

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

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

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

两种方法的不同之处在于,在第一种方法中,您忘记了Set位。因此,解决方案:

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