View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Jerry W. Lewis Jerry W. Lewis is offline
external usenet poster
 
Posts: 837
Default Round Function (Significant Figures) for Large Numbers

You can use WorksheetFunction.Round to call the Excel round function from VBA.

I have posted code to handle the full range of inputs in the VBA Round
function
http://groups.google.com/group/micro...7fce6145b70d69
Note that the VBA round function handles exact ties differently from the
Excel round function.
It also is less buffered against undisplayable differences due to binary
approximations (also addressed in my code).

The earliest reference I know of to this method of sigfig rounding is
http://groups.google.com/group/micro...244c8f41e91025
though I would be very interested evidence of earlier independent discoveries.

Jerry

" wrote:

Hi

In a previous thread* I have found the formula to round a number to a
set degree of significant figures (not decimal places... woot!),
however, I would like the equivalent code for VBA so that I can write
my own function, rather than having to remmeber the formula every time.

*
http://groups.google.co.uk/group/mic...2b0ee70b4a2af6

Formula: (Thanks to J.E. McGimpsey for this stroke of genius)
For N significant figures, use:
=ROUND(A1, N - 1 - INT(LOG10(ABS(A1))))

The code I have written (note that Function statements have been
commented out so I can debug and a msgbox function added to check the
result):

Sub breakitdown()

'Function SigFig(x, SigFigs)

'chuck in a number for debugging
x = 654321

'set defult sigfigs if none provided
If SigFigs = "" Then SigFigs = 3

SigFig = Round(x, ((SigFigs - 1) - Int(Log10(Abs(x)))))

'check result
MsgBox SigFig

'End Function

End Sub

This works fine for small numbers (rounding decimal places), but,
unlike the worksheet function, VBA will not accept a negative integer
for the number of decimal places in the Round function. (I found this
out by using the altered step-by-step formula below to find the exact
point the code was falling over)

temp1 = Abs(mydata)
temp2 = Log10(temp1)
temp3 = Int(temp2)
temp4 = SigFigs - 1
temp5 = temp4 - temp3
SigFig = Round(mydata, temp5)

Does anyone know of a function in VBA that will round large numbers to
a set number of significant figures? I.e. 654321 becomes 654000

Thanks in advance

Rob