多个QueryDef / CopyFromRecordset复制数据

时间:2017-09-27 15:05:09

标签: excel-vba access-vba vba excel

所以,我在Excel 2013中遇到了一些DAO问题。我在下面粘贴了我的代码以供审核。

我遇到的问题是,第二个CopyFromRecordset与第一个数据重复。例如:

  • 首先是1500行
  • 第二次拉动应该是来自不同表的1200行
    • 第二次拉动是与第一次拉动相同的1500行

我试图找出问题,并在DB / Qry / RS变量中添加了一些监视,它们都是checkout,以及SQL行。我为每个变量添加了一些“close”和“Nothing”行,以尝试清除我遗漏的任何残留数据。我甚至尝试使用CutCopyMode=False语句清除剪贴板;这也没用。

关于下面代码的其他所有内容都有效,除了它正在吐出的数据。我还需要从同一个数据库中执行另外两次拉动,但是在我搞砸之前想要弄清楚这些,哈哈。

提前感谢您的帮助!!

Dim dt_EndDate As Date

Dim wkbk_PMC As Workbook


Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset
Dim MyTableDef As DAO.TableDef

dt_EndDate = DateSerial(Year(Date), Month(Date) + 2, 0)

Application.ScreenUpdating = True
Application.StatusBar = "Generating Reports..."
Application.ScreenUpdating = False

Set wkbk_PMC = Workbooks.Add

    With wkbk_PMC
        .SaveAs Filename:=CreateObject("Wscript.Shell").specialfolders("Desktop") & "\" & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & " - Coordinator Weekly Meeting"
    End With

Set MyDatabase = DBEngine.OpenDatabase("N:\Database\Coordinator Reports.accdb")
Set MyQueryDef = MyDatabase.QueryDefs("qry_DRReport_CNP")

With MyQueryDef
    .Parameters("[dt_EndDate]") = dt_EndDate
End With

Set MyRecordset = MyQueryDef.OpenRecordset

wkbk_PMC.Sheets(1).Range("A3").CopyFromRecordset MyRecordset
For i = 1 To MyRecordset.Fields.Count
    wkbk_PMC.Sheets(1).Cells(2, i).Value = MyRecordset.Fields(i - 1).Name
Next i

MyRecordset.Close           ' Added to attempt to sever all connection to previous DB/Qry/RS
MyQueryDef.Close            ' Added to attempt to sever all connection to previous DB/Qry/RS
MyDatabase.Close            ' Added to attempt to sever all connection to previous DB/Qry/RS
Set MyRecordset = Nothing   ' Added to attempt to sever all connection to previous DB/Qry/RS
Set MyQueryDef = Nothing    ' Added to attempt to sever all connection to previous DB/Qry/RS
Set MyDatabase = Nothing    ' Added to attempt to sever all connection to previous DB/Qry/RS

Set MyDatabase = DBEngine.OpenDatabase("N:\Database\Coordinator Reports.accdb")
Set MyQueryDef = MyDatabase.QueryDefs("qry_DRReport_CCP")

With MyQueryDef
    .Parameters("[dt_EndDate]") = dt_EndDate
End With

Set MyRecordset = MyQueryDef.OpenRecordset

lRow = wkbk_PMC.Sheets(1).Range("A" & Rows.Count).End(xlUp).Row

wkbk_PMC.Sheets(1).Range("A" & (lRow + 1)).CopyFromRecordset MyRecordset

MyRecordset.Close
MyQueryDef.Close
MyDatabase.Close

0 个答案:

没有答案