简体   繁体   中英

Excel VBA to copy and paste values with iterations

My problem is the following: I have some data in an Excel sheet (1 column, multiple rows) which I want to copy and paste to a new sheet (sheet2) still in a row. Values are changing all the time (Montecarlo simulations) so I need to introduce some iterations as well.

This is my code:

Sheets("sheet1").Range("a2:z2").Copy
With Sheets("sheet2")
For i = 1 To 10000
    .Range("A" & i + 1 & ":B" & i + 1 & ":C" & i + 1 & ":D" & i + 1 & ":E" & i + 1 & ":F" & i + 1 & ":G" & i + 1 & ":H" & i + 1 & ":I" & i + 1 & ":J" & i + 1 & ":K" & i + 1 & ":L" & i + 1 & ":M" & i + 1 & ":N" & i + 1 & ":O" & i + 1 & ":P" & i + 1 & ":Q" & i + 1 & ":R" & i + 1 & ":S" & i + 1 & ":T" & i + 1 & ":U" & i + 1 & ":V" & i + 1 & ":W" & i + 1 & ":X" & i + 1 & ":Y" & i + 1 & ":Z" & i + 1 & ":AA" & i + 1 & ":AB" & i + 1 & ":AC" & i + 1 & ":AD" & i + 1 & ":AE" & i + 1 & ":AF" & i + 1).PasteSpecial Paste:=xlPasteValues
Next i
End With

This is of course not flexible at all since i need to specify precisely how many values I have Range("a2:z2") and I need to write all the letters corresponding to the paste columns (A to AF)

What I would like to achieve is the following: -) Can I copy values from a column instead of a row? for example sheet 1 column A -) Can I have the VBA to check how many values there are instead of me having to specify it ? maybe soemetimes there are 10 and sometimes 50 -) When I paste values in sheet 2 is there a way where I do not need to specify all column names but just have excel figure it out itself?

The task is basically the following: -) Count how many values are there in column A (or whatever column contains raw data) -) Copy those values -) Paste values in first available row in sheet 2 -) Specify number of iterations -) copy and past N-times corresponding to number of iterations so I have as many output rows as iterations

I am sure it should be fairly easy with a simple code, but I could not find it out myself Thank you very much beforehand

Use the .PasteSpecial property to transpose your copy selection.

    Dim lcol As Long
    Dim j As Integer 'Number of iterations
    Dim searchRange As Range
    Dim transposeRange As Range
    'Find the last value in the column
    lcol = Range("A:A").SpecialCells(xlCellTypeLastCell).Row
    j = 'Set your iteration number

    For i = 1 To j 'Count through all iterations
        Sheet1.Range("A1:A" & lcol).Copy
        'Transpose the selection to paste into row
        Sheet2.Rows(i).PasteSpecial transpose:=True
    Next i

If you don't know the number of iterations, call this as a sub in the Worksheet.Change event, which will run every time the values in the column change.

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