我需要用另一个工作簿中命名范围内的单元格填充数组的值。到目前为止,我所没有的对我有用:
Dim vArray() as Variant
vArray = Workbooks("Book2").Worksheets("Sheet1").Range("myRange")
Debug.Print vArray(1) 'yields error
也没有运气:
vArray = Workbooks("Book2").Names("myRange")
或者
vArray = Workbooks("Book2").Names("myRange").RefersToRange
最佳答案
尝试将打印行更改为此:
Debug.Print vArray(1, 1)
这是您如何遍历它们的方法:
Sub Test()
Dim vArray() As Variant
vArray = Range("myRange")
Dim i As Long
For i = LBound(vArray, 1) To UBound(vArray, 1)
Debug.Print vArray(i, 1)
Next
End Sub
* 编辑*
要使用“Book2”而不必激活它,您可以执行以下操作:
Sub Test()
Dim vArray() As Variant
Dim rng As Range
Dim wbk As Workbook
Set wbk = Excel.Application.Workbooks("Book2.xls")
Set rng = wbk.Worksheets("Sheet1").Range("myRange")
vArray = rng
Dim i As Long
For i = LBound(vArray, 1) To UBound(vArray, 1)
Debug.Print vArray(i, 1)
Next
End Sub
要从另一本书打开book2,请将第5行更改为:
Set wbk = Excel.Application.Workbooks.Open("C:\Users\myname\Desktop\Book2.xls")