Excel VBA从命名范围填充数组

时间:2013-09-26 21:06:26

标签: excel excel-vba vba

我需要使用另一个工作簿中命名区域的单元格填充数组的值。到目前为止,我所拥有的并不适合我:

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

2 个答案:

答案 0 :(得分:5)

尝试将打印行更改为:

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")

答案 1 :(得分: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