为导出到Excel的交叉表查询提供以下代码。在代码的开头,我引用了我在QBE网格中创建的一个名为 1ACTMasterQuery 的查询,一切正常。
但是,我已经在一个名为 MasterPivot 的字符串中将该SQL复制到VBA中,并且它执行得很好。但我希望以下内容使用 PivotMaster 而不是 1ACTMasterQuery 。
如何更改代码以便使用 PivotMaster 中的数据?
该错误表示无法找到 PivotMaster 。我知道这是一个选择查询,需要伪造系统,以便它认为它是一个表,如:
CurrentDb.CreateQueryDef "SKbyYrByMo", SKbyYrByMo
尝试了几次猜测,但都没有奏效。
SKbyYrByMo = "TRANSFORM Sum([1ACTMasterQuery].Extension) AS SumOfExtension"
& _
" SELECT [1ACTMasterQuery].Year, [1ACTMasterQuery].Sku,
Sum([1ACTMasterQuery].Extension) AS [Total Of Extension]" & _
" FROM 1ACTMasterQuery" & _
" GROUP BY [1ACTMasterQuery].Year, [1ACTMasterQuery].Sku" & _
" PIVOT [1ACTMasterQuery].MonthNo"
'Create the view/query to like a table object
CurrentDb.CreateQueryDef "SKbyYrByMo", SKbyYrByMo
'-----Set Query Running Status---------------------------------------------
-
Me.QueryStatus.Visible = True
Me.QueryStatus.SetFocus
Me.QueryStatus.BackColor = vbGreen
Me.QueryStatus.Text = " Processing"
' ------------------------------------------- --------------------------------
DoCmd.TransferSpreadsheet _
acExport, _
acSpreadsheetTypeExcel12Xml, _
"SKbyYrByMo", _
"C:\Users\John\Desktop\RSExcel.xlsx", _
True
CurrentDb.QueryDefs.Delete "SKbyYrByMo"
'-----End query Staus-------------------------------------------------------
Me.QueryStatus.Text = " "
Me.SKbYbM.SetFocus
Me.QueryStatus.Visible = False
MsgBox "Complete"
由于
答案 0 :(得分:1)
考虑以下例程,使用QueryDefs创建和销毁所需的查询。此外,在SQL语句中使用表别名来减少长度并轻松替换源表:
Dim qdef As QueryDef
Dim strSQL As String
' DELETE QUERIES IF THEY EXIST
For Each qdef in CurrentDb.QueryDefs
If qdef.Name = "SKbyYrByMo" Or qdef.Name = "PivotMaster" Then
CurrentDb.QueryDefs.Delete qdef.Name
End If
Next qdef
' CREATE PivotMaster QUERY
strSQL = "SELECT d.Account_Number, d.Transaction_Type, d.Sku, " & _
" d.Extension, d.Year, d.MonthNo" & _
" FROM dbo_Transaction_Table d"
Set qdef = CurrentDb.CreateQueryDef("PivotMaster", strSQL)
Set qdef = Nothing ' SAVE NEW QUERY
' CREATE SKbyYrByMo QUERY
strSQL = "TRANSFORM Sum(t.Extension) AS SumOfExtension" & _
" SELECT t.Year, t.Sku, Sum(t.Extension) AS [Total Of Extension]" & _
" FROM 1ACTMasterQuery t" & _
" GROUP BY t.Year, t.Sku" & _
" PIVOT t.MonthNo"
' REPLACE SOURCE TABLE
strSQL = Replace(strSQL, "1ACTMasterQuery", "PivotMaster")
Set qdef = CurrentDb.CreateQueryDef("SKbyYrByMo", strSQL)
Set qdef = Nothing ' SAVE NEW QUERY
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
"SKbyYrByMo", "C:\Users\John\Desktop\RSExcel.xlsx", True