文書の過去の版を表示しています。


How to copy range form one sheet another

excelシートのある範囲(Range)を同じWorkbookの別シートに張り付ける方法を紹介する。
Range.Copyメソッドを使うだが、範囲のlastRowを判断するロジックとコピー先の最後列を計算するロジックを入れる。
想定している使い方としては、マスタシートの必要な部分のみピックアップして別シートにコピーすることだ。
例えば、OLEDBドライバを使いExcelをDBとして使う場合、255番目以降のデータは認識されない問題がある。
そもそも、Accessが255Column制限があるための制限らしい。
こういった場面で、全Columnではなく一部分のColumnを参照する場合は、
選択列をマスタシートからコピーして新しいテーブルを構成するのが有効な回避策(Work-around)となりうる。
さって、序論が長くなってしまったが、簡単なコードなので、コードを見てみよう。

Code snippet

Sub AddTable(source As Worksheet, target As Worksheet, startCol As Long, endCol As Long)
    Dim lastCol, lastRow As Long
 
    With source
        ' Find the last row of data
        lastRow = source.Cells(Rows.Count, startCol).End(xlUp).Row
        ' Find the last column of data
        lastCol = target.Cells(1, Columns.Count).End(xlToLeft).Column
        If (lastCol = 1) Then lastCol = 0
        .Range(.Cells(1, startCol), .Cells(lastRow, endCol)).Copy _
            Destination:=target.Cells(1, lastCol + 1)
    End With
End Sub

QR Code
QR Code study:vba:copy (generated for current page)