Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Round Function

In one of my programs I need to calculate the average on a range of numbers. The problem is that sometimes the answer comes out to a huge decimal and I need to try and get that down to two decimal places maximum.

I've seen something called Excel.WorksheetFunction.Round(...) but as far as I know it only works with a specific number or a specific cell. I was wondering if anyone knew how to implement this so that it will round all decimals in a range of cells.

Excel.WorksheetFunction.Round(ActiveSheet.Range(g_first_Function_Col & "2:" & g_first_Function & g_totalRow).Select, 2)

The code above attempts to use the round function on a range of cells. The g_first_Function_Col is some column (like column "H") and g_totalRow is the last row that has any values in it. When I try to run this bit of code it tells me "=" expected. Essentially I'm trying to select an entire column and round it.

Thank you,

Jesse Smothermon

like image 509
Jesse Smothermon Avatar asked Mar 18 '11 21:03

Jesse Smothermon


1 Answers

There are two ways that you can do that.

-Select your range and change the number format:

Range("myrange").Select
Selection.NumberFormat = "0.00"

-Loop through all the cells in your range and apply the Round function to each of them. In VBA you won't be able to use the Round function on a whole range at one time.

For Each currentcell In myRange
    currentcell.Value = Math.Round(currentcell.Value, 2)
Next

(pseudocode above; you'll need a better For..Next loop to loop through all the cells in your range.)

like image 165
Stewbob Avatar answered Oct 14 '22 00:10

Stewbob