![](/img/trans.png)
[英]VBA Excel Store Range as Array, extract cell values for formula. Offset for other variables
[英]Using VBA to assign range of cell values to array of variables
我对VBA很新,要在这里忍受我。
我想给一组变量分配一组范围的值,即。 运行简短的代码来简化以下内容
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
但是教程将其删除(因为它是关于名称的教程),建议我按如下方式填充它
sample(1)=activesheet.range("C7").value
sample(2)=activesheet.range("C7").value
等等
我发现下面的讨论是在正确的轨道上回答我的任务,但我无法应用它来解决我的问题。 ( 循环的Excel VBA数组范围 )
作为后续注释,我最终尝试为这些变量赋值,以便在以下过程中使用,而不是每次都声明和分配它们。
谢谢!
尝试这样的事情:
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
你应该 :
对于该范围的每个单元格,检索您的数据
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
编辑:我缩进代码以正确显示它
以上的其他方式你只能使用:
Arr = ActiveWorksheet.Range("C1:C20").Value
然后你可以直接使用:
Arr(i,1)
其中i
是C1到C20范围!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.