6

我需要使用另一个工作簿中命名范围内的单元格填充数组的值。到目前为止,我所拥有的对我不起作用:

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
4

2 回答 2

7

尝试将打印行更改为:

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")
于 2013-09-26T21:38:26.770 回答
4

另一种方法.. 测试

Sub Test()
Dim vArray As Range
Dim rng As Range

  With ActiveSheet
  Set vArray = .Range("myRange")
  For Each rng In vArray
  Debug.Print rng.Value
  Next rng
  End With

End Sub
于 2013-09-27T01:35:19.710 回答