【问题标题】:vba counter loop for columns列的vba计数器循环
【发布时间】:2020-08-14 19:16:05
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这个answer可以帮忙吗?

标签: excel vba


【解决方案1】:

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

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

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

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

如 cmets 中所述,使用 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

【讨论】:

  • 我还将通过指定将对象绑定到其父对象来帮助用户(使用With 块)。
  • @ScottHoltzman 是的,当然。我认为 with 块有时是品味问题,有时是节省时间的问题。很好地介绍所有选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多