将数据从一个工作簿传输到另一个工作簿

时间:2015-12-10 18:45:41

标签: database vba copy transfer

我目前正在编写一个代码,希望能够做到这一切:

  1. 从数据库文件中,让我选择并打开源文件
  2. 转到“源表”,并从源文件中复制A,B,D,E和F列上的所有数据
  3. 返回数据库文件(数据表)并找到A,B,D,E和F列上的下一个空行。
  4. 然后逐列粘贴所有数据
  5. 关闭源文件而不保存
  6. 我目前的代码满足要求1&仅限5。这是我目前的代码:

    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
    

1 个答案:

答案 0 :(得分:0)

  

'我不知道该放什么

    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