VBA:选择列范围中的最后一个单元格并复制工作表中的单元格

时间:2016-10-31 17:38:00

标签: vba

我有几个列,我正在尝试将每列的最后一个单元格复制到一个列中(在另一个工作表中)。

这是我的代码不起作用(我循环遍历行和列):

 Sub lastcell()

 Dim lRow As Long
Dim lCol As Long

Dim i As Long


Worksheets("input").Select

 With Worksheets("input")
 Worksheets("output").Cells.ClearContents

 lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

 Set ColRange = .Range(.Cells(1, 1), .Cells(5, lCol))

For Each ccol In ColRange
  lRow = .Cells(.Rows.Count, ccol).End(xlUp).Rows.Count

   For i = 2 To 6
    Worksheets("output").Cells(i, 1) = .Cells(lRow, ccol)

 Next i
Next ccol


End With

End Sub

1 个答案:

答案 0 :(得分:1)

你有一个太多的循环。

lRow = .Cells(.Rows.Count, ccol).End(xlUp).Rows.Count应以Row而不是.Rows.Count

结尾

同样使用Set ColRange = .Range(.Cells(1, 1), .Cells(5, lCol)),您将循环遍历每列5次。 5应为1

无需在代码开头激活或选择输入表。

应宣布

ccol

Sub lastcell()

Dim lRow As Long
Dim lCol As Long
Dim ccol as Range
Dim i As Long   

With Worksheets("input")
    Worksheets("output").Cells.ClearContents
    lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    Set colrange = .Range(.Cells(1, 1), .Cells(1, lCol))
    i = 1
    For Each ccol In colrange
        lRow = .Cells(.Rows.Count, ccol.Column).End(xlUp).Row
        Worksheets("output").Cells(i, 1).Value = .Cells(lRow, ccol.Column).Value
        i = i + 1
    Next ccol


End With

End Sub

我们可以通过简单的for循环进一步简化它:

Sub lastcell()

Dim lRow As Long
Dim lCol As Long
Dim i As Long

With Worksheets("input")
    Worksheets("output").Cells.ClearContents
    lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    For i = 1 To lCol
        lRow = .Cells(.Rows.Count, i).End(xlUp).Row
        Worksheets("output").Cells(i, 1).Value = .Cells(lRow, i).Value
    Next i

End With

仅供参考,也可以使用公式来完成。

在输出表的第一个单元格中输入以下公式:

=INDEX(input!A:Z,MAX(IFERROR(MATCH("ZZZ",INDEX(input!A:Z,0,ROW(1:1))),0),IFERROR(MATCH(1E+99,INDEX(input!A:Z,0,ROW(1:1))),0)),ROW(1:1))

然后将公式复制/拖动,直至获得0 s