无法从函数内部访问新的工作簿

时间:2016-07-01 17:20:12

标签: excel vba scope

我正在尝试从其他工作簿访问信息并在中心位置填充该信息。具体来说,我正在尝试编写一个可以在将返回目标工作簿的UsedRange.Count的单元格中使用的函数。

问题在于,当我尝试指向工作簿对象时,我不断获得错误#9或#91。我99.99%确定我正确命名文件。

更重要的是,当我将代码作为Sub而不是函数运行时,它可以正常工作。

这是工作Sub:

Sub test()

    Dim wb As Workbook
    Dim wb2 As Workbook

    Dim fileName As String
    Dim rootDir As String

    Dim BigSum As Integer

    rootDir = ActiveWorkbook.Path
    fileName = "TestSheet1"

    Set wb = ActiveWorkbook

    MsgBox rootDir

    On Error Resume Next

    Set wb2 = Workbooks(fileName & ".xlsx")

    Set wb2 = Workbooks.Open(rootDir & "\Test1\" & fileName & ".xlsx")

    MsgBox wb2.Worksheets("Sheet1").Range("A3").Value2

    BigSum = wb2.Worksheets("Sheet1").UsedRange.Count - 2

    MsgBox BigSum

End Sub

现在这是功能的一个例子:

Function Adder(exTension As String, fileName As String) As Integer

    Dim wb As Workbook
    Dim wb2 As Workbook

    Dim rootDir As String

    rootDir = ActiveWorkbook.Path

    Set wb = ActiveWorkbook

    On Error GoTo errHandler

    Set wb2 = Workbooks(fileName & ".xlsx")

    Set wb2 = Workbooks.Open(rootDir & "\" & exTension & "\" & fileName & ".xlsx")

    Adder = wb2.Worksheets("Sheet1").UsedRange.Count - 2

    MsgBox Adder

errHandler:

    MsgBox Err.Number

    Resume exitHere

exitHere:

End Function

据我所知,这些之间没有真正的区别。这是范围问题吗?

0 个答案:

没有答案