Search code examples
databasevbacopytransfer

Transfer data from one workbook to another


Im currently working on a code that hopefully does this set of things:

  1. From the database file, ask me to select and open a source file
  2. Go to Source Sheet, and copy all data on column A, B, D, E, and F from the source file
  3. Go back to the Database file(Data Sheet) and locate the next empty row on column A, B, D, E, and F.
  4. Then paste all data column by column
  5. Close the source file and not save

The current code that I have satisfies requirement 1 & 5 only. Here is my current code:

Option Explicit


    Sub Copy_data()
    Dim databasewkb As Workbook, sourcewkb As Workbook
    Dim Ret1, Ret2
    Dim srcws As Worksheet ' Variable for source workbook worksheets
    Dim databasews As Worksheet ' Variable for portal workbook worksheets
    Dim srcLR As Long ' last row of the source worksheet
    Set databasewkb = ActiveWorkbook

    '~~> Get the first File
    Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select the source file file")
    If Ret1 = False Then
        ' Tell the user why the code has been terminated
        MsgBox ("Sorry, unable to proceed without a file.")
        Exit Sub
    End If

    ' Open the Source file
    Set sourcewkb = Workbooks.Open(Ret1)

    ' Set the source worksheet
    Set srcws = sourcewkb.Sheets("Source Sheet")

    ' Set the first destination worksheet
    Set databasews = databasewkb.Sheets("Data Sheet")

With srcws
    ' Find the last row of data in the Source worksheet
    srcLR = .Cells(Rows.Count, 1).End(xlUp).Row   

    'im not sure what to put here



    ' close the source workbook, don't save any changes
    sourcewkb.Close SaveChanges:=False

    ' Clear the objects
    Set srcws = Nothing
    Set sourcewkb = Nothing
    Set databasews = Nothing
    Set databasewkb = Nothing
    End Sub

Solution

  • 'im not sure what to put here

        srcLR = .Cells(.Rows.Count, 1).End(xlUp).Row 
        ' Beware here, use ".Rows.Count" instead of "Rows.Count", because
        ' I suspect you are opening an old workbook in compatibility mode
    
        Dim srcRange as Range, destRange as Range
    
        Set srcRange = .Range("A1:B" & srcLR)
        Set destRange = databasews.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
        srcRange.Copy destRange
    
        Set srcRange = .Range("D1:F" & srcLR)
        Set destRange = destRange.Offset(0, 3)
        srcRange.Copy destRange
    
    End With