【问题标题】:function "openfile" returning workbook ends with run-time error '91'函数“openfile”返回工作簿以运行时错误“91”结尾
【发布时间】:2013-07-31 05:27:06
【问题描述】:

我想通过以下功能打开并参考工作簿。只有函数会产生运行时错误“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

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

非常感谢您的帮助!

【问题讨论】:

    标签: vba excel


    【解决方案1】:

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

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

    【讨论】:

    • 好的,这很愚蠢,我很确定我检查过了,但我想我没有......谢谢,现在可以了!
    • @grinsbaeckchen 您在函数内部完成了它,并且(我猜)认为它已经足够了;但是新的赋值 WBTest = 返回的变量也需要它。这是每个人都会犯的愚蠢错误(至少,一次):)
    • 这可能是一个旧答案,但谢谢您,先生,您让我免于一个小时的捂脸!
    • @DaMachk 欢迎您,有礼貌的绅士。它确实是一个旧的,虽然不像使用 Set 那样古老(我猜你是 VBA 的新手)。
    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2013-04-16
    相关资源
    最近更新 更多