2012-03-26 102 views
2

我需要從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 
+1

連接字符串使用'&'而不是'+'。所以endCell =「B13:B」&endCell – 2012-03-26 17:26:33

回答

1

使用變調功能:

nums = Application.WorksheetFunction.Transpose(Range(endCell).value) 
+2

不知道如何與問題相關... – assylias 2012-03-26 17:26:02

+0

如果不使用移調,結果將是變體的變體... – 2012-03-26 17:29:34

+0

'nums = Range(「A1:B5」)'將返回從' nums(1,1)'(= A1)到'nums(5,2)'(= B5)... – assylias 2012-03-26 17:31:17

4

您不必這樣做。只需執行以下操作:

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 
+0

+1但值得測試的是endCell比'varValues = Range(endCell).Value'之前的1個單元大。 Esle錯誤結果。 – brettdj 2012-03-27 02:40:06

+0

@brettdj感謝您指出這一點;我編輯了答案。 – phoog 2012-03-27 13:52:20

0

從您的代碼開始,你可以循環通過以下方式在陣列上:

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 
0

我不確定這是更好還是更清潔。

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