VBA 使用 Access 将一个 Excel Sheet 的记录追加到另一个

VBA Using Access To Append Records from One Excel Sheet To Another

我有一个 Access DB,我正在尝试将单个文件夹中的多个工作表复制到主 excel 文件

我首先为工作簿构建一个名为 filedetails 的文件位置数组,然后打开每个文件并将内容粘贴到主文件中。因为我不希望文件相互粘贴。主工作簿上的起始位置始终与前一个粘贴位置相差 1。所有工作簿都在同一个工作目录中,因此代码设置为停止将主工作簿复制到自身

代码在 xlSht2.Range(Selection, Selection.End(xlToRight)).Select 失败并显示错误消息

Run-Time error '424' Object Required

Set xlApp = CreateObject("Excel.Application")

'## Open Working File
Set xlBook_A = xlApp.Workbooks.Open(strWF)
Set xlSht = xlBook_A.Worksheets(1)

' Open Each Sheet and Copy it into the Workbook (Except Worksheet into itself)
For intRecord = 1 To UBound(filedetails)
If (filedetails(1, intRecord)) <> strWF Then
    Set xlBook_B = xlApp.Workbooks.Open(filedetails(1, intRecord))
    Set xlSht2 = xlBook_B.Worksheets(1)

    ' After the rows have been pasted, a new starting point not "A2" will need to be set
    ' This offset will be done after each copy and paste giving an Append operation to MS Excel
    ' So Sheet A wont overwrite Sheet B
    xlSht2.Range(Selection, Selection.End(xlToRight)).Select
    xlSht2.Range(Selection, Selection.End(xlDown)).Select
    xlSht2.Selection.Copy Destination:=xlSht.Range("A1").End(xlDown).Offset(1, 0)

End If

Next intRecord

谁能看出我哪里出错了?

复制前不需要Select区域。下面的示例应该适用于您的情况。

Option Explicit

Sub test()
    Dim xlShtMaster As Worksheet
    Dim xlSht2 As Worksheet
    xlSht2.UsedRange.Copy Destination:=xlShtMaster.Range("A1").End(xlDown).Offset(1, 0)
End Sub

在您的代码中,删除 Endif 之前的 3 行并包含此内容

xlSht2.Range(Selection, Selection.End(xlToRight)).Select
if xlSht.Range("F1").End(xlDown).row=Rows.Count
    xlSht2.Range(Selection, Selection.End(xlDown)).Copy xlSht.Range("F1")
Else    
    xlSht2.Range(Selection, Selection.End(xlDown)).Copy xlSht.Range("F1").End(xlDown).Offset(1, 0)
Endif