我在VBA中有一个程序,它根据用户在表单中的下拉列表(报表名称和分组条件)上选择的内容来运行报表。此外,我有一个按钮,用户选择可以转移到Excel。 如果查询存在,我想测试的过程部分如下:
If Not IsNull(Me.cmbGroup.Value) Or Me.cmbGroup.Value = "" Then
strSQL = "SELECT * FROM qryCrossTotGroup WHERE [Group]='" & Me.cmbGroup.Value & "'"
'MsgBox strSQL
With MyDatabase
.QueryDefs.Delete ("tmpOutQry")
Set MyQueryDef = .CreateQueryDef("tmpOutQry", strSQL)
End With
'Step 3: Open the query
Set MyRecordset = MyDatabase.OpenRecordset(strSQL)
'Step 4: Clear previous contents
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.Workbooks.Add
.Sheets("Sheet1").Select
'Step 5: Copy the recordset to Excel
.ActiveSheet.Range("A2").CopyFromRecordset MyRecordset
'Step 6: Add column heading names to the spreadsheet
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
End If
我想测试一下查询" tmpOutQry"存在是为了删除它。有人那行代码吗?
答案 0 :(得分:4)
您没有使用临时查询,因此您可以将第一步减少到:
strSQL = "SELECT * FROM qryCrossTotGroup WHERE [Group]='" & Me.cmbGroup.Value & "'"
'MsgBox strSQL
'Step 3: Open the query
Set MyRecordset = MyDatabase.OpenRecordset(strSQL)
答案 1 :(得分:2)
我尝试了这段代码并且工作了:
{{1}}