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

前端 未结 3 1025
迷失自我
迷失自我 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
    
    0 讨论(0)
  • 2021-01-05 17:12

    You should :

    • Define the range you want to retrieve data
    • For each cell of the range, retrieve your datas

      dim tab() As string, cell as range, i as integer
      i = 0
      redim tab(0)
      for each cell in ActiveWorksheet.Range("C1:C20")
          tab(i) = cell
          i = i + 1
          redim preserve tab(i)
      next
      

    edit : I indent the code to display it correctly

    0 讨论(0)
  • 2021-01-05 17:19

    Additional way to the above you can only use:

    Arr = ActiveWorksheet.Range("C1:C20").Value
    

    Then you can directly use:

    Arr(i,1) where i is C1 to C20 range!

    0 讨论(0)
提交回复
热议问题