I am looking to read in a range consisting of a single row on cells A1:G1
into an array with 10 rows and then output the results on the same sheet in cells A2:G11
. The data in the input row changes as it is based on formulas containing random numbers. I'm told that the fastest way to do this is with an array. Not sure how to do that. So far I have the code shown below. This doesn't work because it won't recalculate the input data before it pastes it into the output cells so it keeps pasting the same values over and over. What is the best way to tackle this?
Sub MyRange()
Dim DataInput As Variant
Dim NumberOfSims As Long, i As Long
Application.Calculation = xlManual
NumberOfSims = 10
DataInput = Range("DataInput").Value
For i = 1 To NumberOfSims
Range(Cells(1 + i, "A"), Cells(1 + i, "g")).Value = DataInput
Application.Calculate
Next i
End Sub
DataInput
never changes because DataInput = Range("DataInput").Value
is outside the loop, so the same values will get pasted over and over.
Move it inside and it will update with each iteration.
Sub MyRange()
Dim DataInput As Variant
Dim NumberOfSims As Long, i As Long
Application.Calculation = xlManual
NumberOfSims = 10
For i = 1 To NumberOfSims
DataInput = Range("DataInput").Value
Range(Cells(1 + i, "A"), Cells(1 + i, "G")).Value = DataInput
Application.Calculate
Next i
End Sub
You can avoid using an array altogether and just transfer the value:
For i = 1 To NumberOfSims
Range(Cells(1 + i, "A"), Cells(1 + i, "G")).Value = Range("DataInput").Value
Application.Calculate
Next i
EDIT:
Instead of continually re-calcing and rereading from the sheet, you could read the formulas into an array, Evaluate
them and then write back to the the sheet all at once.
Perhaps something like this:
Sub MyRange()
Dim NumberOfSims As Long, NumberOfCols As Long
NumberOfSims = 5000
NumberOfCols = Range("DataInput").Columns.Count
Dim InputFormulas() As Variant
InputFormulas = Range("DataInput").Formula
Dim OutputValues() As Variant
ReDim OutputValues(1 To NumberOfSims, 1 To NumberOfCols)
Dim R As Long, C As Long
For R = 1 To UBound(OutputValues, 1)
For C = 1 To UBound(OutputValues, 2)
OutputValues(R, C) = Application.Evaluate(InputFormulas(1, C))
Next C
Next R
Range("A2").Resize(UBound(OutputValues, 1), UBound(OutputValues, 2)).Value = OutputValues
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.