gpt4 book ai didi

Excel VBA 从命名范围填充数组

转载 作者:行者123 更新时间:2023-12-02 09:34:47 25 4
gpt4 key购买 nike

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

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

关于Excel VBA 从命名范围填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com