如何访问其他工作簿中的数据



我的函数接受工作簿作为输入。但我无法迭代工作簿中的值。我得到的错误是"对象变量未设置"。附言:我不能使用范围,因为范围是未知的。

Sub Test (wb as workbook)
Dim sheet as worksheet
Dim value as Integer
sheet = wb.worksheet(1)
value = sheet.Cells(1,1).Formula
return value
End sub

您的代码有几个问题:

  1. 您得到的错误是因为您声明了Dim sheet As WorksheetWorksheet是一个对象,并且对象需要像一样是Set

    Set sheet = wb.worksheet(1)
    
  2. 您将变量value定义为Integer,然后尝试将.Formula读取到其中,即StringInteger不能容纳公式。我想你想改为阅读.Cells(1,1).Value

  3. VBA没有return,您需要设置函数Test = value

  4. 您使用的是过程Sub,而不是函数,因此它不能返回任何值。您需要将其更改为Function

我认为你最终应该得到这样的东西:

Public Function ReadMyValue(ByVal wb As Workbook) As Double 'or Long
Dim ws As Worksheet
Set ws = wb.Worksheet(1) 'use set for objects!
Dim Value As Double 'or Long !!! but the same as your function is declared !!!
Value = ws.Cells(1, 1).Value
ReadMyValue = Value 'return the value to your function
End Function

你可以这样测试:

Public Sub TestMyFunction()
Debug.Print ReadMyValue(ThisWorkbook) 'will output the value of A1 of the first worksheet in this workbook.
End Sub

最新更新