简体   繁体   中英

For Each In: Is it possible to run through a single-column range and paste multiple columns, starting with that first FOR cell?

I've been having trouble trying to optimize a certain part of my code. I am performing a Monte Carlo simulation and I want to copy the values of a range a repeated number of times. To do this, I've used a For Each In structure. Below is a minimal example.

sub example()
Dim live As Excel.Range 'the range to be copied in each For Each In
Dim acell as Excel.Range 'For range
Set live = Range("C5:P5")

For Each acell in Range("B9:B90")
acell.value=live.value
Next acell

End Sub

The problem is that live spans multiple columns, while acell is just one cell; what ends up happening is just the first column is copied, the rest are blank. I have also used For Each acell in XYZ.rows where XYZ is a previously defined range of multiple columns and rows. However, this is considerably slower.

Is it possible to run through a single-column range and paste multiple columns, starting with that first cell?

Is this what you are looking for?

Sub example()
Dim live As Excel.Range 'the range to be copied in each For Each In
Dim acell As Excel.Range 'For range
Set live = Range("C5:P5")

live.Copy
Range("B9").PasteSpecial xlPasteValues, , , True

End Sub

It might be best to read C5:P5 in as an array:

Sub CopyLoop()
    Dim copyRng(), targetRng As Range, cl As Range

    copyRng = Range("C5:P5") 'Read in as array
    Set targetRng = Range("B9:B90")

    For Each cl In targetRng
        Range("B" & cl.Row & ":O" & cl.Row) = copyRng
    Next cl
End Sub

You're almost there; you're just missing a tiny change in your code. You have to Resize the target range. Instead of

bcell.value=live.value ' bcell (presumably a typo) is only 1 column wide

use

acell.Resize(1, live.Columns.Count).Value = live.Value

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