[英]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.