VBA - 返回对WorkBook

时间:2016-05-30 20:23:14

标签: excel vba

我想调用一个返回工作簿或对该工作簿的引用的函数。但是,我无法使用函数返回的工作簿设置值'wb'。

Public Sub TestScript()

    Dim wb As Workbook    
    wb = GetWorkBook()

End Sub


    Function GetWorkBook() As Workbook

    Dim db2 As Workbook
    Dim xlApp As Excel.Application
    Set xlApp = GetObject(, "Excel.Application")

    Dim xlWB As Excel.Workbook
    For Each xlWB In xlApp.Workbooks
        If xlWB.Name = "Test.XLSX" Then
            Set db2 = xlWB
        End If
    Next xlWB

    Set xlApp = Nothing
    Set xlWB = Nothing

    GetWorkBook = db2


    End Function

给出:

  

运行时错误91:   对象变量或未设置块变量

1 个答案:

答案 0 :(得分:6)

您忘了两次使用set语句:

Public Sub TestScript()

    Dim wb As Workbook
    Set wb = GetWorkBook()

End Sub

Function GetWorkBook() As Workbook

Dim db2 As Workbook
Dim xlApp As Excel.Application
Set xlApp = GetObject(, "Excel.Application")

Dim xlWB As Excel.Workbook
For Each xlWB In xlApp.Workbooks
    If xlWB.Name = "Test.XLSX" Then
        Set db2 = xlWB
    End If
Next xlWB

Set xlApp = Nothing
Set xlWB = Nothing

Set GetWorkBook = db2

End Function

每当您将对象分配给变量(由此引用它)时,您必须使用set语句(https://stackoverflow.com/a/349636/1153513)。

示例:

  1. Set rngYourRangeVariable = Thisworkbook.Worksheets("Sheet1").Range("A1:C4")
  2. Set shtSomeSheet = Thisworkbook.Worksheet("Sheet1")
  3. Set conSomeADOconnection = New ADODB.Connection