我想在 VBA 中填充 Array ,使用 for each-loop 但无法做到这一点
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 中每一列的最后一个单元格的值。
代码更新
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