For Each In:是否可以运行单列范围并粘贴多个列,从第一个FOR单元格开始?
我一直在尝试优化我的代码的某个部分时遇到了麻烦。 我正在执行蒙特卡罗模拟,我想复制范围的值重复的次数。 为此,我使用了For Each In结构。 下面是一个简单的例子。
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
问题是live
跨越多个栏目,而acell
只是一个单元格; 最后发生的只是第一列被复制,其余都是空白的。 我也在For Each acell in XYZ.rows
使用了For Each acell in XYZ.rows
其中XYZ
是先前定义的多个行和列的范围。 但是,这是相当慢的。
从第一个单元格开始,是否可以遍历单列范围并粘贴多个列?
你快到了; 你只是错过了你的代码中的一个小小的改变。 您必须Resize
目标范围。 代替
bcell.value=live.value ' bcell (presumably a typo) is only 1 column wide
使用
acell.Resize(1, live.Columns.Count).Value = live.Value
这是你想要的?
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
将C5:P5
读入数组可能是最好的:
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