使用VBA复制和粘贴循环计算的结果

时间:2015-03-16 20:54:25

标签: excel vba excel-vba

我有一个VBA计算循环,以重新计算单元格500(或任何迭代次数)。对于每次重新计算,都有一个输出,我希望在循环完成后进行记录。我尝试了几种不同的方法,但我似乎无法做到正确。这是我到目前为止的一个例子。

Private Sub CommandButton1_Click()
   Dim Iteration As Integer, i As Integer
   Iteration = Range("C4")

   For i = 1 To Iteration
     Range("C14,C15,C16,C17,C18,C19,C20").Calculate
     Range("C20").Copy
     Range("J" & Rows.Count).End(xlUp).Offset(1).Select.PasteSpecial  xlPasteValues
   Next i

End Sub

3 个答案:

答案 0 :(得分:1)

我认为唯一的问题是你选择与粘贴特殊相同的行。试试这个:

Private Sub CommandButton1_Click()
Dim Iteration As Integer, i As Integer
Iteration = Range("C4")


For i = 1 To Iteration
  Range("C14,C15,C16,C17,C18,C19,C20").Calculate
Range("C20").Copy
Range("J" & Rows.Count).End(xlUp).Offset(1,0).PasteSpecial Paste:=xlPasteValues
Next i
End Sub

答案 1 :(得分:0)

试试这个:

Private Sub CommandButton1_Click()
   Dim Iteration As Integer, i As Integer
   Dim val as Variant
   Iteration = Range("C4")

   For i = 1 To Iteration
       Range("C14,C15,C16,C17,C18,C19,C20").Calculate
       val = Range("C20").Value

       Debug.print "i: " & i & " val: " & val
       Range("J" & Rows.Count).End(xlUp).Offset(1) = val
   Next i
End Sub

如果在即时窗口中没有显示正确的值,则问题出在其他地方。显然,如果代码按预期工作,请删除debug.print语句。

答案 2 :(得分:0)

Private Sub CommandButton1_Click()
Dim Iteration As Integer, i As Integer
    Iteration = Range("C4")

Dim RLog As Range              ' prepare a range for the log
    Set RLog = [C22]           ' or wherever you want to start the log range

    For i = 1 To Iteration
        Range("C14,C15,C16,C17,C18,C19,C20").Calculate

        RLog(i,1) = [C20]      ' write the current result to the range (short notation [C20] is aequivalent to Range("R20")
    Next i
End Sub