问题
I want the function to take a range of cells as an argument and return their product. Let's assume the following value for cells:
A1=5
A2=2
A3=3
Let's call the function Multiply
.
=Multiply(A1:A3)
will return 30 (=5×2×3).
What is the code for this? I'm just trying to familiarize myself with the syntax and this will help out a lot.
Edit: figured it out:
Function multiply(rng As Range)
multiplied = 1
For Each cell In rng
multiplied = multiplied * cell.Value
Next
multiply = multiplied
End Function
回答1:
You can use the VBA
version of PRODUCT
directly, ie
MsgBox WorksheetFunction.Product([a1:a3])
回答2:
You can use excel worksheet functions.
The default behaviour of SUMPRODUCT
if there is only a single range provided is to return the sum so you can just pass the range to SUMPRODUCT
this way:
WorksheetFunction.Sumproduct(**your range goes here**)
回答3:
OK for =PRODUCT
, which does the job (SUMPRODUCT
will NOT do what the initial fellow asked).
But, just for fun, using the properties of the math functions EXP and LN we have that if
X = A1*B1*C1 then
LN(X) = LN(A1)+LN(B1)+LN(C1)
and
X = EXP(LN(X)) or
X = EXP(LN(A1)+LN(B1)+LN(C1))
so just put in a cel: =EXP(SUM(LN(A1:C1)))
and voilà! (you must use CTRL+SHIFT+ENTER)
回答4:
If you insist of writing your own function then try the following. It loads all the values into memory first and thus should work faster.
Public Function RngProduct(ByRef r as Range) as Double
Dim vals() as Variant, res as Double
vals = r.Value
Dim i as Long, N as Long
N = r.Rows.Count
res = #1
For i=1 to N
res = res * vals(i,1)
Next i
RngProduct = res
End Function
来源:https://stackoverflow.com/questions/20320662/simple-vba-function-that-returns-product-of-range-value