I guarantee that you're mot the first person who's needed to calculate this - or any other math function you can think of - in Excel. A search for "weighted geometric mean excel" lead me to an answer (likely the same place you got the function).
It's good to see that you attempted to solve this yourself, however it's not the "Sum" section that's preventing your function from working.
Debugging Your VBA Function:
I'm afraid there are a number of things wrong with your code. That number is "Nine".
Most importantly, you transposed your formulas criteria in your explanation.
The parameter that starts with the W
is the Weight, and the other parameter is the Value.
If you want to use parameters with more than 1 cell, you use Range
(not Double
).
You cannot assign a value directly to a cell (or change a cell in any other way) from within a function. Functions return values to the cell from which it was called.
Address(False, False)
isn't going to accomplish anything productive in this case.
(You need better understanding of the purpose of relative vs. absolute references.)
Instead of using: Range(Cells(2,1), Cells(2,3)).Address(False,False)
...you could use A2:C2
because they mean exactly the same thing (and always will).
Therefore, all this:
Range("A1").Formual="Sum("& Range(Cells(2,1), Cells(2,3)).Address(False,False)&")
...can be shortened to: [A1]=[A2]+[B2]+[C2]
...because they are mean exactly the same thing (and always will).
You're using worksheet functions in VBA, which is fine in some cases
...but the function is Application.WorksheetFunction.Sum
.
The natural logarithm function LN
accepts only one value when used one it's own
...not a "list" (or range of cells)
You should use Option Explicit
at the top of each module, especially when learning or troubleshooting; it would have helped you catch at least a couple of these mistakes.
Also you have a couple unnecessary sets of parentheses, but that's not a big deal.
So, you could work on fixing all of that, or better yet, you could use it as a worksheet function and save yourself (or someone else) a lot of work for no reason.
Using the Worksheet Function
Syntax:
=EXP(SUMPRODUCT(
WeightRange
,LN(
ValueRange
))/SUM(
WeightRange
))
- note that the same
*WeightRange*
is entered twice.
- the
*WeightRange*
and *ValueRange*
must both be the same size.
Example:
If:
- cells A1 to A5
contains your values, and,
- cells B1 to B5
contain the weights for the values, and,
- you wanted the Weighted Geometric Mean in cell C1
...then in C1
you would enter:
=EXP(SUMPRODUCT(B1:B5,LN(A1:A5))/SUM(B1:B5))
I suspect that this will suffice as a solution, now that we've walked through it, but if you have an actual reason that you need this calculation to take place within a VBA Function then by all means let me know and me will figure it out. :-)