简体   繁体   中英

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). 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.

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:

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

Note: In the For loop above, you change the value from 5 to your desired number to loop the code that many times. But test this with 5 first and see if its working as expected.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM