Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

excel - Not able to create array from 1 cell range in VBA

I have code that reads ranges and converts them to arrays for processing. It unfortunately fails when the range only has one cell.

To boil down the problem, consider the following ranges (r1, r2) with respectively 1 and 2 cells, that I want to convert to arrays a1 and a2, respectively:

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

How can I ensure that an array will be created even if the range has only one element?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to check how many cells there are in your Range you are trying to convert to array, use If r2.Cells.Count > 1 Then.

Code

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...