2016-03-14 34 views
1

我有一个前端数据库设置,供用户提取关于他们上传的信息列表的数据。导出功能正常工作,除非他们希望结果转到打开的工作簿中,而不保存数据而添加数据表。问题是,当我在宏未运行之前或之后运行查询时,创建的查询具有数据。但是,当宏运行时,查询不会返回任何内容。下面是我使用的最新VBA。请检阅并告知我错过了什么。 谢谢访问VBA:记录集应该不是空的

微软Office - 访问:2010

有效参考库:

  • Visual Basic应用程序
  • 的Microsoft Access 14.0对象库
  • OLE自动化
  • Microsoft Excel中14.0对象库
  • Microsoft Office
  • 14.0 Access数据库引擎对象库

宏:

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 

回答

0

精氨酸,我找到了答案。经过一周的尝试,我决定发布这个问题,然后在一个小时后我发现了这个问题。

问题出在SQL的“Where”子句中。我需要把表单的值作为一个变量,并将其写入等式中。由于某些原因,宏在运行时,表单的引用部分被视为没有值。所以没有任何回报。

因此,SQL的下面一行:

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

变成了:

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

谢谢你让我交的。