我想填充在VBA陣列,使用每個循環,但不能這樣做,在這行如何在Excel宏中使用For Each Loop With Formula填充多維數組?
Dim MyArray() As Variant
Dim RowCounter As Integer
Dim ColCounter As Integer
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("B10:Z97")
RowCounter = 0
ColCounter = 0
ReDim MyArray(rRng.Rows.Count, rRng.Columns.Count) 'Answer by @varocarbas
For Each rCol In rRng.Columns
For Each rCell In rCol.Rows
If IsNumeric(rCell.Value) And (Not (IsEmpty(rCell.Value))) And (Len(rCell.Value) <> 0) Then
'ReDim Preserve MyArray(RowCounter, ColCounter) -- Old Logic which cause Error
MyArray(RowCounter, ColCounter) = rCell.Value
RowCounter = RowCounter + 1
Else
'Debug.Print rCell.Value & " is not an Integer" & vbNewLine
End If
Next rCell
ColCounter = ColCounter + 1
RowCounter = 0
Next rCol
但ReDim Preserve MyArray(RowCounter, ColCounter)
我下標錯誤,當ReDim Preserve MyArray(1, 0)
我想讀Excel中的值填充數組,然後進行一些計算,並通過計算Excel的值來更新Excel中每列的Last Cell的值。
代碼更新
Function RunSquareOfVariance(temperature As Integer, cellValue As Variant) As Double
RunSquareOfVariance = "=IF((" & temperature + cellValue & ")<0,0,(" & temperature + cellValue & "))*IF((" & temperature + cellValue & ")<0,0,(" & temperature + cellValue & "))"
End Function
如果代碼內我改變波紋線現在
MyArray(RowCounter, ColCounter) = RunSquareOfVariance(StantardTemperature, rCell.Value)
MYARRAY(0,0)值存儲爲=IF((-16.8)<0,0,(-16.8))*IF((-16.8)<0,0,(-16.8))
內
但我想存儲公式的值Withing MyArray(0,0) = ValueOftheFormula
爲什麼不是頂部只有一次REDIM的好辦法?使用ReDim MYARRAY(rRng.Columns.Count,rRng.Rows.Count) – varocarbas
@varocarbas:是的,我這樣做,我發現區域。 –
你也可以使用'myArray = Range(「B10:Z97」)'!最快的。 –