英文:
How to display totals row using VBA?
问题
有没有办法使用VBA添加列的总和?我知道可以使用Application.CommandBars.ExecuteMso "RecordsTotals"
来添加"总计"行,但我似乎找不到添加我想要的列总和的方法。我尝试使用CurrentDb.QueryDefs("queryName").Fields("Quantity").Properties("AggregateType").Value = 0
,但没有任何反应。感谢任何帮助。顺便说一下,这是我的代码。
Private Sub Command1_Click()
Dim db As DAO.Database: Set db = CurrentDb
Dim CustName As String
Dim qDef As DAO.QueryDef
If IsNull(Combo2.Value) Then
MsgBox "Please Choose a customer"
Else
CustName = DLookup("[FullName]", "TblCustomer", _
"[CustID] = " & Combo2.Value)
For Each qDef In db.QueryDefs
If qDef.Name = "TblCustomer Query" Or qDef.Name = "TblLocationId Query" Then
Else
DoCmd.DeleteObject acQuery, qDef.Name
End If
Next
Set qDef = db.CreateQueryDef(CustName)
qDef.sQl = "SELECT OrderID, SaleDate, ProductID, UnitPrice, Quantity, Quantity * UnitPrice As TotalPrice FROM TblOrderDetails WHERE CustID = " & Combo2.Value & ""
Application.RefreshDatabaseWindow
DoCmd.OpenQuery CustName, acViewNormal
DoCmd.SelectObject acQuery, CustName
Application.CommandBars.ExecuteMso "RecordsTotals"
CurrentDb.QueryDefs(CustName).Fields("Quantity").Properties("AggregateType").Value = 2
End If
End Sub
英文:
is there a way to add sum of a column using VBA? I know I could use 'Application.CommandBars.ExecuteMso "RecordsTotals"
to add the "Total" row, but I can't seem to find the way to add the sum of a column that I want. I tried using CurrentDb.QueryDefs("queryName").Fields("Quantity").Properties("AggregateType").Value = 0
but nothing happened. I'd appreciate any help guys. By the way, here's my code.
Private Sub Command1_Click()
Dim db As DAO.Database: Set db = CurrentDb
Dim CustName As String
Dim qDef As DAO.QueryDef
If IsNull(Combo2.Value) Then
MsgBox "Please Choose a customer"
Else
CustName = DLookup("[FullName]", "TblCustomer", _
"[CustID] = " & Combo2.Value)
For Each qDef In db.QueryDefs
If qDef.Name = "TblCustomer Query" Or qDef.Name = "TblLocationId Query" Then
Else
DoCmd.DeleteObject acQuery, qDef.Name
End If
Next
Set qDef = db.CreateQueryDef(CustName)
qDef.sQl = "SELECT OrderID, SaleDate, ProductID, UnitPrice, Quantity, Quantity * UnitPrice As TotalPrice FROM TblOrderDetails WHERE CustID = " & Combo2.Value & ""
Application.RefreshDatabaseWindow
DoCmd.OpenQuery CustName, acViewNormal
DoCmd.SelectObject acQuery, CustName
Application.CommandBars.ExecuteMso "RecordsTotals"
CurrentDb.QueryDefs(CustName).Fields("Quantity").Properties("AggregateType").Value = 2
End If
End Sub
答案1
得分: 2
如果你只想在打开查询后显示这些内置总计,这里是解决方案:
DoCmd.OpenQuery CustName, acViewNormal
CommandBars.ExecuteMso "RecordsTotals"
英文:
A bit late, but...
If you just want to display those built-in totals after opening the query, here's the solution:
DoCmd.OpenQuery CustName, acViewNormal
CommandBars.ExecuteMso "RecordsTotals"
答案2
得分: 0
我使用SQL中的UNION解决了这个问题。谢谢大家的帮助!
英文:
I solved this by using UNION in sql. Thanks for helping out guys!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论