如何将一系列单元格分配给数组

时间:2018-03-08 04:39:32

标签: arrays vba excel-vba range excel

我尝试使用以下代码创建一个简单的1D数组。

Sub Button3_Click()
Dim search() As Variant
Dim data() As Variant
Worksheets("IO List").Activate
Set searchitems = ActiveSheet.Range("A1", "U1")
Set ExportData = ActiveSheet.Range("A3", "U3")
search = searchitems.Value
MsgBox (search(1))
End Sub

消息框只是检查数组的值,但是我抛出了错误:运行时错误' 9':下标或范围

2 个答案:

答案 0 :(得分:2)

将数组值分配给数组时,即使您只收集单列或单行的值,始终也会获得二维数组。

Application.transpose将来自单个列的行数据转换为基于1的1-D数组。使用它两次会将列数据从单行转换为基于1的1-D数组。

Dim search As Variant, data As Variant

Worksheets("IO List").Activate
search  = Application.transpose(Application.transpose(Range("A1", "U1").value))
data = Application.transpose(Application.transpose(Range("A3:U3").value))

MsgBox search(1)

答案 1 :(得分:0)

Excel已针对使用2D Variant数组进行了优化。

您几乎总是希望Value2而不是Value。 (见TEXT vs VALUE vs VALUE2 – Slow TEXT and how to avoid it

您还可以使用With块来避免激活工作表:

Sub Button3_Click()
    Dim search() As Variant
    Dim data() As Variant
    With Worksheets("IO List")
        search = .Range("A1", "U1").Value2
        ExportData = .Range("A3", "U3").Value2
    End With
    MsgBox search(1, 1)
End Sub