使用VBA将单元格值的范围分配给variables数组

我对VBA很新,在这里忍受着我。

我想给一组variables赋值一组范围,即。 运行一个简短的代码来简化以下内容

Dim Sample 1 as string Sample1 = activeworksheet.range("C17").value Dim Sample 2 as string Sample2 = activeworksheet.range("C18").value} 

等等

遵循excelfunctions.net教程,我知道我可以缩短声明

 Dim Sample(1 to 20) as a string 

但教程放在那里(因为它是一个关于名字的教程),build议我填充它如下

 sample(1)=activesheet.range("C7").value sample(2)=activesheet.range("C7").value 

等等

我发现下面的讨论是在正确的轨道上回答我的追求,但是我很难将其应用于我的情况。 ( 用于循环的Excel VBA数组范围 )

作为一个后续的说明,我最终试图为这些variables赋值,以便在下面的过程中使用,而不是每次声明和赋值。

谢谢!

你应该 :

  • 定义您想要检索数据的范围
  • 对于范围的每个单元格,检索您的数据

     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 

编辑:我缩进代码,以正确显示它

尝试这样的事情:

 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 

另外,如果您知道要放入数组的范围,则可以简单地将数组设置为该范围:

 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