Excel VBA-复制/粘贴行

时间:2018-12-19 19:26:18

标签: excel vba excel-vba

我希望将包含单元格A1:G1的单行读入包含10行的数组中,然后将结果输出到单元格A2:G11的同一张纸上。输入行中的数据基于包含随机数的公式而更改。有人告诉我,最快的方法是使用数组。不知道该怎么做。到目前为止,我有下面显示的代码。这是行不通的,因为在将输入数据粘贴到输出单元格之前,它不会重新计算输入数据,因此会不断重复粘贴相同的值。解决此问题的最佳方法是什么?

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 

1 个答案:

答案 0 :(得分:1)

DataInput永远不会更改,因为DataInput = Range("DataInput").Value在循环 之外,因此相同的值将一遍又一遍地粘贴。

将其移入内部,它将随着每次迭代进行更新。

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

您可以避免完全使用数组,而只需传输值:

For i = 1 To NumberOfSims
    Range(Cells(1 + i, "A"), Cells(1 + i, "G")).Value = Range("DataInput").Value
    Application.Calculate
Next i

编辑:

您可以将公式读入数组,Evaluate,然后一次写回到表中,而不是不断地从表中重新计算和重新读取表。

也许是这样的:

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