How to multiply all records of a single field in A

2019-08-01 06:02发布

问题:

I want to multiply all records of a single field in Access 2010. I tried mult(Field name) and product(field name) to no avail. Can anyone help me is there any function in Access to do so?

Example:
I have a table having the field S1

S1 
---
557
560
563
566
569
572
575
578
581

and the output should be in another table having the field result

Result
--------
6.25E+24

回答1:

Unfortunately, there is no PRODUCT() function in Access SQL that would allow you to do

SELECT PRODUCT([S1]) AS Result FROM [YourTable]

However, you can use VBA to "roll your own" DProduct() domain aggregate function, similar to the built-in DSum() function:

Option Compare Database
Option Explicit

Public Function DProduct(Expr As String, Domain As String, Optional criteria) As Variant
    Dim SQL As String, Result As Double
    Dim cdb As DAO.Database, rst As DAO.Recordset
    On Error GoTo DProduct_Error
    Set cdb = CurrentDb
    SQL = "SELECT " & Expr & " AS Expr1 FROM [" & Domain & "]"
    If Not IsMissing(criteria) Then
        SQL = SQL & " WHERE " & criteria
    End If
    Set rst = cdb.OpenRecordset(SQL, dbOpenSnapshot)
    If rst.BOF And rst.EOF Then
        DProduct = Null
    Else
        Result = 1
        Do Until rst.EOF
            Result = Result * rst!Expr1
            rst.MoveNext
        Loop
        DProduct = Result
    End If
    rst.Close
    Set rst = Nothing
    Set cdb = Nothing
    Exit Function

DProduct_Error:
    DProduct = Null
End Function

Testing with the sample data in your question

?DProduct("S1", "YourTable")
 6.24666417941851E+24