简体   繁体   中英

Excel VBA to copy column to existing workbook

I have Workbook, source.xlsm , Worksheet "test1" Column A6:A20 that I need to copy to another WorkBook located on my C:... named dest.xlsx , Worksheet "Assets" , Column "I" . I need to be able to copy the data and be able to add to the column without overwriting the previous data copied. Any help would be a life saver.

Sub Align()
    Dim TargetSh As String

    TargetSh = "Assets"

    For Each WSheet In Application.Worksheets

        If WSheet.Name <> TargetSh Then
            WSheet.Select
            Range("A6:A20").Select
            Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
            Selection.Copy
            Sheets(TargetSh).Select
            lastRow = Range("I65532").End(xlUp).Row
            Cells(lastRow + 1, 1).Select
            ActiveSheet.Paste
        End If
    Next WSheet
End Sub

Is this what you are trying? I have not tested it but I think it should work. Let me know if you get any errors.

Sub Sample_Copy()
    Dim wb As Workbook, wbTemp As Workbook
    Dim ws As Worksheet, wsTemp As Worksheet
    Dim lastRow As Long

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("test1")

    '~~> Change path as applicable
    Set wbTemp = Workbooks.Open("C:\dest.xlsx")
    Set wsTemp = wbTemp.Sheets("Assets")

    lastRow = wsTemp.Range("I" & Rows.Count).End(xlUp).Row + 1

    ws.Range("A6:A20").Copy wsTemp.Range("I" & lastRow)

    Application.CutCopyMode = False

    '~~> Cleanup
    wbTemp.Close savechanges:=True
    Set wb = Nothing: Set wbTemp = Nothing
    Set ws = Nothing: Set wsTemp = Nothing
End Sub

HTH

Sid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM