How to code a worksheet expression in vba?

JenniferMurphy

Well-known Member
Joined
Jul 23, 2011
Messages
2,691
Office Version
  1. 365
Platform
  1. Windows
I am working on a fairly simple UDF to calculate weighted ratings. The expression in the worksheet is:
Excel Formula:
=SUM(Weights*(Ratings<>0))
where both Weights and Ratings are ranges.

This vba code works:
VBA Code:
Public Function WtdRtgS(prRatings As Range, prWeights As Range) As Double
Dim SumWts As Double
SumWts = Application.WorksheetFunction.Sum(prWeights)
but this gets a Value error:
VBA Code:
SumWts = Application.WorksheetFunction.Sum(prWeights * (prWeights <> 0))
What do I need to do to be able to do in the UDF the calculation that works in the sheet?

Thanks
 

Excel Facts

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.
Thanks, Marcelo. That works.

So the rule is that I can execute worksheet functions by themselves, but if they are part of an expression, I need to assemble it as a text string and then pass that to the Evaluate function. Right?
 
Upvote 0
You can't compare arrays and values or use simple operators on arrays directly in VBA. So the issue in your original code was both the prWeights <> 0 part and the attempt to multiply that by another range/array.
 
Upvote 0
You can't compare arrays and values or use simple operators on arrays directly in VBA. So the issue in your original code was both the prWeights <> 0 part and the attempt to multiply that by another range/array.
Got it, thanks.

This limitation seems like another example of a stunningly mediocre product from M$FT. And they have had a few years to work on it.
 
Upvote 0
I have no doubt it does.
 
Upvote 0

Forum statistics

Threads
1,224,828
Messages
6,181,204
Members
453,022
Latest member
RobertV1609

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top