【问题标题】:Transfer data from one workbook to another将数据从一个工作簿传输到另一个工作簿
【发布时间】:2015-12-10 18:45:41
【问题描述】:

我目前正在编写一个希望能做这组事情的代码:

  1. 从数据库文件中,让我选择并打开一个源文件
  2. 转到源表,并从源文件中复制 A、B、D、E 和 F 列中的所有数据
  3. 返回数据库文件(数据表)并在 A、B、D、E 和 F 列上找到下一个空行。
  4. 然后逐列粘贴所有数据
  5. 关闭源文件而不保存

我拥有的当前代码仅满足要求 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

【问题讨论】:

  • C列不是操作的一部分?
  • 嗨,A.S.H,实际上没有。我故意跳过了那个,因为我只想复制给定列上的那些。
  • 嗨。您可以尝试将我的答案中给出的代码放在代码的缺失部分。顺便说一句,不要忘记End With ;)
  • 让我确认一下。这些列是完全独立的吗?我的意思是,源表中同一行上的数据值,它们不需要保持在目标表中的同一行上吗??
  • 是的,他们需要保持在同一行。

标签: database vba copy transfer


【解决方案1】:

我不知道该放什么

    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

【讨论】:

  • 嗨 ASH,我的 (.Rows.Count,1) 有错误,它说编译错误:无效或不合格的参考
  • 请确保将其放在With bloc 中?
  • 哦,知道了,抱歉。顺便说一句,你碰巧知道另一种方法来自动化这个过程。我的意思是而不是打开文件。我的工作簿将自动打开我希望它打开的文件并获取上面的所有数据并执行相同的操作,但在工作簿打开时执行此操作。我有什么意义吗?呵呵对不起
  • 关于您提供的代码的问题,我想我在说明中错过了这一点。有没有不复制列标题的方法?每列的第一行是标题。
  • 只需将A1:B 替换为A2:B 并将D1:F 替换为D2:F。我不太明白你的另一个问题。无论如何,我建议你现在让它工作,一旦完成,如果你不知道如何修改它,你可以问另一个问题;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
相关资源
最近更新 更多