Using VBA to assign range of cell values to array of variables

前端 未结 3 1102
迷失自我
迷失自我 2021-01-05 16:47

I\'m very new to VBA, to bear with me here.

I want to assign a set of variables the value of a set of ranges ie. run a brief code to simplify the following



        
3条回答
  •  醉话见心
    2021-01-05 17:09

    Try something like this:

    Sub test()
    Dim sampleArr(1 To 20) As String
    Dim i As Integer
    Dim rng As Range, cel As Range
    
    i = 1
    Set rng = Range("C1:C20") 
    
    For Each cel In rng
        sampleArr(i) = cel.Value
        i = i + 1
    Next cel
    For i = LBound(sampleArr) To UBound(sampleArr)
        Debug.Print sampleArr(i)
    Next i
    

    Also, if you know the range you want to put into an array, you can simply set an array to that range:

    Sub test()
    Dim sampleArr() As Variant
    Dim i As Integer
    Dim rng As Range, cel As Range
    
    i = 1
    Set rng = Range("C1:C20") ' Note, this creates a 2 Dimensional array
    
    sampleArr = rng ' Right here, this sets the values in the range to this array.
    
    For i = LBound(sampleArr) To UBound(sampleArr)
        Debug.Print sampleArr(i, 1) ' you need the ",1" since this is 2D.
    Next i
    
    End Sub
    

提交回复
热议问题