A simple VBA function that returns the product of a range value

I want the function to take a range of cells as an argument and return its product. Assume the following value for cells:

A1=5 
A2=2 
A3=3 

Call by function Multiply.   =Multiply(A1:A3)will return 30 (= 5 × 2 × 3).

What is the code for this? I'm just trying to get familiar with the syntax, and that will help a lot.

Edit: found out:

Function multiply(rng As Range)

    multiplied = 1

    For Each cell In rng
        multiplied = multiplied * cell.Value
    Next

    multiply = multiplied

End Function
+4
source share
4 answers

You can use the VBAversion PRODUCTdirectly, i.e.

MsgBox WorksheetFunction.Product([a1:a3])
+4
source

You can use excel sheet functions.

SUMPRODUCT , , - , SUMPRODUCT :

WorksheetFunction.Sumproduct(**your range goes here**)
+1

=PRODUCT, (SUMPRODUCT , ).

, , EXP LN, ,

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))

cel: =EXP(SUM(LN(A1:C1))) voilà! ( CTRL + SHIFT + ENTER)

+1

, . , , .

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
0

All Articles