[英]excel - Macro - How to iterate over rows & a range of cells
i've got a question. 我有一个问题。
I've got the names of sheets in my workbook in a sheet named "Summary". 我的工作簿中的工作表名称为“摘要”。 I've got some stats in a sheet called "Stats".
我在名为“统计信息”的工作表中有一些统计信息。 I wanna loop over the names in summary sheet, select each sheet, then copy the values from B2:M2 from "stats" page, transpose copy it to column D2 in the sheet selected from "Summary" sheet.
我想遍历摘要表中的名称,选择每个表,然后从“统计”页面中复制B2:M2中的值,转置后将其复制到从“摘要”表中选择的表中的D2列。 Then I want to move to next sheet from the list of sheets from "Summary" page, copy B3:M3 & copy as transpose the D2 column in the selected sheet & so forth.
然后,我想从“摘要”页面的工作表列表中移至下一个工作表,复制B3:M3并复制为转置所选工作表中的D2列,依此类推。
I've managed to get this bit of code for it. 我已经设法获得了这段代码。 It's not compelte.
这不是强迫的。 I'm unable to figure out how to increment from
B2:M2
to B3:M3
to B4:M4
& so on. 我无法弄清楚如何从
B2:M2
增至B3:M3
增至B4:M4
等。
Please can someone help me. 请有人帮我。 I've never written VB code before.
我以前从未写过VB代码。
Sub transpose()
Dim MyCell As Range, MyRange As Range
Dim row_counter As Long, col_counter As Long
Set MyRange = Sheets("Summary").Range("A1")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
row_counter = 2
col_counter = 2
For Each MyCell In MyRange
Sheets("Stats").Select
Range("B2:M2").Select
Selection.Copy
Sheets(MyCell.Value).Select
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, transpose:=True
row_counter = row_counter + 1
col_counter = col_counter + 1
Next MyCell
End Sub
See below code (which is your code with the addition of offset). 请参见下面的代码(这是带有偏移量的代码)。
Offset
will let you increment from B2:M2
to B3:M3
asb so on. Offset
使您可以从B2:M2
递增到B3:M3
依此类推。
I replaced your row and col variable with just x
since you only move by row. 我只用
x
替换了row和col变量,因为您只能逐行移动。
Sub transpose() Dim MyCell As Range, MyRange As Range Dim x as long Set MyRange = Sheets("Summary").Range("A1") Set MyRange = Range(MyRange, MyRange.End(xlDown)) x = 0 For Each MyCell In MyRange Sheets("Stats").Select Range("B2:M2").Offset(x, 0).Select Selection.Copy Sheets(MyCell.Value).Select Range("D2").Select Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _ False, transpose:=True x = x + 1 Next MyCell End Sub
Also you can try this: 您也可以尝试以下方法:
Dim MyCell, MyRange as Range Dim wb as Workbook Dim ws, wsTemp, wsStat as Worksheet Dim x as Long Set wb = Thisworkbook Set ws = wb.Sheets("Summary") Set wsStat = wb.Sheets("Stats") With ws lrow = .Range("A" & .Rows.Count).End(xlUp).Row Set MyRange = .Range("A1:A" & lrow) End With x = 0 For Each MyCell in MyRange Set wsTemp = wb.Sheets(MyCell.Value) wsStat.Range("B2:M2").Offset(x, 0).Copy wsTemp.Range("D2").PasteSpecial xlPasteAll, , , True x = x + 1 Set wsTemp = Nothing Next MyCell End Sub
Already Tested. 已测试。
Hope it does what you want to achieve. 希望它能实现您想要的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.