繁体   English   中英

vba 列计数器回路

[英]vba counter loop for columns

我的代码的目的是复制每一列并将每一列粘贴到 A 列中的另一列下方。

我正在尝试使用计数器循环一次遍历一个列,但我无法弄清楚如何引用每一列来获取列中所有使用的单元格。 对于行非常简单,但对于列,我是否需要将变量设置为字符串并将其更改为字母计数器,或者我可以使用范围格式的数字来引用列?

当我尝试 select 整个列时,下面的代码不起作用。

Sub testing()

Dim i As Integer
Dim lastrow As Integer
Const g As Byte = 2

lastrow = Range("b" & Rows.Count).End(xlUp).Row

For i = g To Cells(1, Columns.Count).End(xlLeft).Column

*Cells(1, i).EntireColumn.End(xlUp).Copy*
Range("a1").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues

Next i

End Sub

Cells(1, i).EntireColumn.End(xlUp).Copy只会复制一个单元格,因为End方法只选择一个单元格。 尝试使用Range object 指定范围的开始(左上)单元格和结束(右下)单元格:

For i = g To Cells(1, Columns.Count).End(xlLeft).Column
   lastRow = cells(1000000, i).end(xlup).row
   Range(Cells(1, i), Cells(lastRow, i)).copy
   Range("a1").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
Next i

编辑:指定我们正在使用的 object 更安全(也是一个好习惯)

dim ws as worksheet
Set ws = Sheets("The name of the sheet I'm working on")

For i = g To ws.Cells(1, ws.Columns.Count).End(xlLeft).Column
   lastRow = ws.cells(1000000, i).end(xlup).row
   ws.Range(ws.Cells(1, i), ws.Cells(lastRow, i)).copy
   ws.Range("a1").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
Next i

如评论中所述,使用With块可以提高字符效率

dim ws as worksheet  
Set ws = Sheets("The name of the sheet I'm working on")

With ws 
   For i = g To .Cells(1, ws.Columns.Count).End(xlLeft).Column
      lastRow = .cells(1000000, i).end(xlup).row
      .Range(ws.Cells(1, i), .Cells(lastRow, i)).copy
      .Range("a1").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
   Next i
End With

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM