VBA使用Access将记录从一个Excel工作表附加到另一个Excel工作表

时间:2016-04-06 13:36:29

标签: excel vba ms-access-2010

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

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

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

  

运行时错误'424'对象必需

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

任何人都可以看到我出错的地方吗?

2 个答案:

答案 0 :(得分:0)

在复制之前,您不需要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

答案 1 :(得分:0)

在您的代码中,删除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