Excel 列的vba计数器循环
我的代码的目的是复制每一列,并将每一列粘贴到A列中另一列的下面 我试图使用计数器循环一次循环一列,但我无法确定如何引用每列以获取列中所有使用的单元格。对于行来说非常简单,但是对于列,我需要将变量设置为string并将其更改为字母计数器,还是可以使用范围格式中的数字引用列 当我尝试选择整个列时,下面的代码不起作用Excel 列的vba计数器循环,excel,vba,Excel,Vba,我的代码的目的是复制每一列,并将每一列粘贴到A列中另一列的下面 我试图使用计数器循环一次循环一列,但我无法确定如何引用每列以获取列中所有使用的单元格。对于行来说非常简单,但是对于列,我需要将变量设置为string并将其更改为字母计数器,还是可以使用范围格式中的数字引用列 当我尝试选择整个列时,下面的代码不起作用 Sub testing() Dim i As Integer Dim lastrow As Integer Const g As Byte = 2 lastrow = Range("
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
单元格(1,i).entireclumn.End(xlUp).Copy
将只复制一个单元格,因为End
方法只选择一个单元格。尝试使用Range
对象指定范围的起始(左上)单元格和结束(右下)单元格:
编辑:指定我们正在使用的对象更安全(也是一个好习惯)
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
如注释中所述,将与
块一起使用可以更高效地使用字符
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
这有帮助吗?我还可以通过指定将对象绑定到其父对象来帮助用户(使用
和块)。@ScottHoltzman是的,当然。我认为,一块砖有时是味道的问题,有时是省时的问题。很好地展示了所有选项。
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