无法在VBA中从1个单元格范围创建数组

时间:2017-01-31 04:05:01

标签: excel-vba vba excel

我有代码读取范围并将它们转换为数组进行处理。 不幸的是,当范围只有一个单元格时会失败。

要解决这个问题,请考虑以下范围(r1,r2)分别为1和2个单元格,我想分别转换为数组a1和a2:

Sub ranges_to_arrays()

    Dim r1 As Range, r2 as Range
    Dim a1() As Variant, a2() as Variant

    Set r2 = Worksheets("test").Range("A1:A2")
    a2 = r2 ' Creates Variant(1 to 2, 1 to 1)

    Set r1 = Worksheets("test").Range("A1")
    a1 = r1 'Fails with a type mismatch

End Sub

即使范围只有一个元素,我怎样才能确保创建数组?

1 个答案:

答案 0 :(得分:0)

您需要检查您尝试转换为数组的范围中有多少个单元格,使用If r2.Cells.Count > 1 Then

<强>代码

Option Explicit

Sub ranges_to_arrays()

    Dim r1 As Range, r2 As Range
    Dim a1() As Variant, a2() As Variant

    Set r2 = Worksheets("test").Range("A1:A2")
    If r2.Cells.Count > 1 Then
        a2 = r2 ' Creates Variant(1 to 2, 1 to 1)
    Else
        ReDim a2(0 To r2.Cells.Count - 1) ' redim array size to 1 (only 1 cell in range)
        a2(0) = r2
    End If

    Set r1 = Worksheets("test").Range("A1")
    If r1.Cells.Count > 1 Then
        a1 = r1 'Fails with a type mismatch
    Else
        ReDim a1(0 To r1.Cells.Count - 1) ' redim array size to 1 (only 1 cell in range)
        a1(0) = r1
    End If

End Sub