[英]How to copy and paste a column of dynamic data (as values) to another column in VBA?
I have formulas in F15:F1649 that, when auto calc is on, the values refresh every time with a mouse click (eg, there is a RAND() function in every cell in F15:F1649).我在 F15:F1649 中有公式,当自动计算打开时,每次单击鼠标都会刷新值(例如,在 F15:F1649 的每个单元格中都有一个 RAND() function)。 I am trying to run a monte carlo simulation that copies the dynamic data in F15:F1649, and pastes it as values to G15:G1649, then copies again and pastes the refreshed data to H15:H1649 and so on until 1000 trials are completed.我正在尝试运行蒙特卡罗模拟,复制 F15:F1649 中的动态数据,并将其作为值粘贴到 G15:G1649,然后再次复制并将刷新的数据粘贴到 H15:H1649,依此类推,直到完成 1000 次试验。
I have recorded a macro myself, but the code is pretty sloppy.我自己录制了一个宏,但是代码很草率。 Please see below for a few example lines of the code:请参阅下面的代码示例行:
Sub Monte_Carlo_Sim()
'
' Monte_Carlo_Sim Macro
'
'
Range("F15").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.End(xlUp).Select
Range("G15").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("H15").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("I15").Select
You already have most of your code generated using the macro recorder.您已经使用宏记录器生成了大部分代码。 If you have a basic understanding of programming, you can add small changes to it and get your desired result.如果您对编程有基本的了解,您可以对其进行一些小的更改并获得您想要的结果。
The problem in your code is that you are manually selecting the location where the copied data needs to be pasted.您的代码中的问题是您正在手动选择需要粘贴复制数据的位置。 Instead of doing that you need let the code identify the last empty column to paste the values and then loop it 1000 times like below:而不是这样做,您需要让代码识别最后一个空列以粘贴值,然后将其循环 1000 次,如下所示:
For i = 1 To 5
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.End(xlToRight).Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next i
The following code: Selection.End(xlToRight).Offset(0, 1).Select
identifies the last non-filled column以下代码: Selection.End(xlToRight).Offset(0, 1).Select
标识最后一个未填充的列
Note: In the For loop above, you change the value from 5 to your desired number to loop the code that many times.注意:在上面的 For 循环中,您将值从 5 更改为所需的数字,以多次循环代码。 But test this with 5 first and see if its working as expected.但是先用 5 测试一下,看看它是否按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.