VBA Round function vs Worksheet Round function

江枫思渺然 提交于 2021-02-07 19:56:25

问题


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:


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.



来源:https://stackoverflow.com/questions/61759694/vba-round-function-vs-worksheet-round-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!