set ws1 As SheetA
set ws2 As Target
With ws1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Lastrow = ws1.Range("B" & Rows.Count).End(xlUp).Row
For i = 1 To Lastcol
For l = 4 To lastrow
ws1.Cells(l, i).Copy ws2.Range("a65536").End(xlUp).Offset(1, 0)
Next l
Next i
我正在尝试将一张纸中的所有列复制到另一张纸下面的另一张纸上。基本上将Sheet1的A列复制到Sheet2的A列,然后将Sheet1的B列复制到Sheet2的A列。
数据从每列中的第A行第4行开始,所以我保持第二个For Loop
从4运行。任何帮助都非常感谢,因为我现在被困了好几个小时。当我运行代码时,它会进入无限循环。
答案 0 :(得分:1)
如果每列的Lastrow
相同(引用B
列),那么您可以尝试以下方法:
With ws1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
Dim i As Long, LastRow2 As Long
For i = 0 To LastCol - 1
With ws2
LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
ws1.Range("A4:A" & LastRow).Offset(0, i).Copy .Range("A" & LastRow2)
End With
Next
您不需要通过嵌套For Loop
逐个复制每个单元格
您可以设置要复制的第一组单元格(Range("A4:A" & LastRow)
),然后使用Offset
仅使用一(1)个循环复制下一列。
如果每列的LastRow
不同,您可以尝试:
Dim LastCol As Long, LastRow As Long
LastCol = ws1.Cells(1, ws1.Columns.Count).End(xlToLeft).Column
Dim i As Long, LastRow2 As Long
For i = 0 To LastCol - 1
LastRow = ws1.Cells(ws1.Rows.Count, i + 1).End(xlUp).Row
With ws2
LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
ws1.Range("A4:A" & LastRow).Offset(0, i).Copy .Range("A" & LastRow2)
End With
Next