VBA Round function vs Worksheet Round function

Viewed 175

I tried to change this Excel function into VBA code

Excel

=ROUND(value,sigfig-(1+INT(LOG10(ABS(value)))))

VBA

Public Function sigfig(val As Double, sigf As Integer) As Double
Dim var As Double
var = Abs(val)
var = Application.WorksheetFunction.Log10(var)
var = Int(var)
sigf = sigf - (1 + var)
sigfig = Round(val, sigf)
End Function

For below 0, both of the Excel and VBA work well. However in VBA, when value (val) is more than sigfig (sigf), it gives me an error. For example, if I want to have 3 sigfig of 55481, it gives #VALUE, instead of 55500.

Please help!

1 Answers

The problem is that the second argument in VBA's Round function can't be negative, but in the worksheet function's version it can.

The solution is simple, just use:

sigfig = Application.WorksheetFunction.Round(val, sigf)

and it will work as intended.

It is significant that Application.WorksheetFunction makes Round available. It does that precisely because the VBA function does not duplicate its functionality exactly. By contrast, Abs would just duplicate the functionality, so you can't call the worksheet version of that function from VBA.

Related