VBA Round Function

孤者浪人 提交于 2019-12-23 07:46:14

问题


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


回答1:


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.)



来源:https://stackoverflow.com/questions/5358043/vba-round-function

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