2016-10-31 9 views
0

複数の列があり、各列の最後のセルを別のワークシートの1つの列にコピーしようとしています。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

あなたは1つのあまりにも多くのループを持っています。

lRow = .Cells(.Rows.Count, ccol).End(xlUp).Rows.Countでは、各列をループに5回を予定しているSet ColRange = .Range(.Cells(1, 1), .Cells(5, lCol))でもない.Rows.Count

を終了する必要があります。 51

である必要があります。コードの冒頭に入力シートを有効にするか、選択する必要はありません。

がCCOLは、私たちは、forループシンプルでも、それをさらに簡素化することができます


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 
に宣言する必要があります。FYIのためだけ

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

関連する問題