How to code a worksheet expression in vba?

JenniferMurphy

Well-known Member
Joined
Jul 23, 2011
Messages
2,687
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

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
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,223,911
Messages
6,175,325
Members
452,635
Latest member
laura12345

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