从数据Excel VBA阵列
问题描述:
我需要从excel中的数据列表中创建一个数组。数据将有不同的长度,所以我将不得不找到它的结尾,然后创建数组。然后我需要遍历数组并使用每个值。 我之前没有使用VBA,所以任何事情都很有帮助。这是我迄今能够得到的结果:从数据Excel VBA阵列
Sub Calc()
Dim endCell As String
endCell = Range("B13").End(xlDown).Row
endCell = "B13:B" + endCell
Dim nums As Variant
nums = Range(endCell)
End Sub
答
您不必这样做。只需执行以下操作:
Dim varValues() as Variant
' ...
varValues = Range(endCell).Value
对于包含多个单元格的范围对象,value属性将返回一个值数组。
如果你不知道的范围是否有不止一个小区,但你想有值的数组不管,你可以写一个函数来实现这一(感谢brettdj为灵感):
Function GetValue(rng As Range) As Variant()
Dim varResult() As Variant
If rng.Cells.Count = 1 Then
ReDim varResult(0 To 0) 'I prefer to be explicit about the base
varResult(0) = rng.Value
Else
varResult = rng.Value
End If
GetValue = varResult
End Function
答
从您的代码开始,你可以循环通过以下方式在阵列上:
Sub Calc()
Dim endCell As String
endCell = Range("B13").End(xlDown).Row
endCell = "B13:B" & endCell
Dim nums As Variant
Dim i As Long
nums = Range(endCell)
For i = LBound(nums,1) To UBound(nums,1)
'do something with nums(i,1)
Next i
End Sub
答
我不确定这是更好还是更清洁。
Sub Calc()
Dim endCell As String
endCell = Range("B13").End(xlDown).Row
endCell = "B13:B" & endCell
Range(endCell).select
For each c in selection
use any attribute of the cells one at a time like, c.value c.formula.....
Next c
End Sub
连接字符串使用'&'而不是'+'。所以endCell =“B13:B”&endCell – 2012-03-26 17:26:33