访问VBA:Recordset应该不是什么都不是

时间:2016-03-14 14:19:41

标签: access-vba ms-access-2010 export-to-excel recordset

我有一个前端数据库设置,供用户提取有关他们上传的信息列表的数据。导出功能正常工作,除了他们希望结果转到打开的工作簿添加带有数据的工作表而不保存。问题是,当我在宏未运行之前或之后运行查询时,创建的查询包含数据。但是,当宏运行时,查询不返回任何内容。我使用的最新VBA如下。请查看并告知我缺少的内容。 谢谢,

MS Office - 访问:2010

Active Reference Library:

  • Visual Basic for applications
  • Microsoft Access 14.0对象库
  • OLE自动化
  • Microsoft Excel 14.0对象库
  • Microsoft Office
  • 14.0访问数据库引擎对象库

宏:

Private Sub ExpFile_Click()
Dim sql2export, s As String, blnExcel, blnWhere As Boolean, qdf As QueryDef, xlApp As Object, ws As Excel.Worksheet
Dim MyDatabase As DAO.Database, MyQueryDef As DAO.QueryDef, MyRecordset As DAO.Recordset
blnWhere = False

If Me. QueryASubform.Visible = True Then 'exceptions
    sql2export = "QueryA"
    blnWhere = True
ElseIf Me. QueryBSubform.Visible.Visible = True Then 'no Program Group for Build ID
    sql2export = " QueryB"
ElseIf Me. QueryCSubform.Visible = True Then 'Bill to and Type report.
    sql2export = " QueryC"
Else: Exit Sub
End If

If blnWhere = False Then
    s = "select * from " & sql2export & " Where (((" & sql2export & ". GPID)=[Forms]![frmFEFindQA]![GPID]));"
Else: s = "select * from " & sql2export
End If

On Error Resume Next
CurrentDb.QueryDefs.Delete "xlsExport"
Set qdf = CurrentDb.CreateQueryDef("xlsExport", s)

Set xlApp = GetObject(, "excel.application")
If (Err.Number = 0) Then
    Set xlApp = GetObject("Excel.Application")
    xlApp.Visible = True
    Set ws = xlApp.Sheets.Add
    Set MyDatabase = CurrentDb
   MyDatabase.QueryDefs.Delete ("xlsExport")
   Set MyQueryDef = MyDatabase.CreateQueryDef("xlsExport", s)
   Set MyRecordset = MyDatabase.OpenRecordset("xlsExport")    ‘<------ empty

    With xlApp
        .ws.Select
        .ActiveSheet.Range("a2").CopyFromRecordset MyRecordset
        For i = 1 To MyRecordset.Fields.Count
            xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
        Next i
    xlApp.Cells.EntireColumn.AutoFit
    End With
Else:
    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = True
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "xlsExport", "C:\Users\" & Environ("USERNAME") & "\Documents\VehInfoExp", True
    xlApp.Workbooks.Open "C:\Users\" & Environ("USERNAME") & "\Documents\InfoExp.xls", True, False
End If
Err.Clear
On Error GoTo 0
Set xlApp = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

Arg,我找到了答案。经过一周的尝试后,我决定发布这个问题,然后一小时后就把它弄清楚了。

问题出在&#34; Where&#34; SQL的子句。我需要将表单的值捕获为变量并将其放入等式中。出于某种原因,当宏运行时,表单的引用部分被视为无效。所以没有回复。

因此,以下SQL行:

s = "select * from " & sql2export & " Where (((" & sql2export & ".GPID)=[Forms]![frmFEFindQA]![GPID]));"

成为:

s = "select * from " & sql2export & " Where (((" & sql2export & ".GPID)=""" & strWhere & """));"

感谢您让我发帖。