VBA 轮函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5358043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:15:36  来源:igfitidea点击:

VBA Round Function

excelvbarounding

提问by Jesse Smothermon

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(...)但据我所知它只适用于特定数字或特定单元格的东西。我想知道是否有人知道如何实现这一点,以便它可以舍入一系列单元格中的所有小数。

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.

上面的代码尝试在一系列单元格上使用 round 函数。g_first_Function_Col 是某个列(如“H”列),g_totalRow 是包含任何值的最后一行。当我尝试运行这段代码时,它告诉我“=”预期。本质上,我试图选择一整列并将其四舍五入。

Thank you,

谢谢,

Jesse Smothermon

杰西·斯莫瑟蒙

采纳答案by Stewbob

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.

- 遍历您范围内的所有单元格,并对每个单元格应用 Round 函数。在 VBA 中,您将无法一次在整个范围内使用 Round 函数。

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

(上面的伪代码;你需要一个更好的 For..Next 循环来循环你范围内的所有单元格。)