VBA 舍入函数

发布于 2024-10-25 05:21:37 字数 508 浏览 2 评论 0原文

在我的一个程序中,我需要计算一系列数字的平均值。问题是,有时答案会出现很大的小数,我需要尝试将其减少到最多两位小数。

我见过名为 Excel.WorksheetFunction.Round(...) 的东西,但据我所知,它仅适用于特定数字或特定单元格。我想知道是否有人知道如何实现这一点,以便它将单元格范围内的所有小数舍入。

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

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

谢谢你,

杰西·斯莫瑟蒙

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乱世争霸 2024-11-01 05:21:37

有两种方法可以做到这一点。

- 选择范围并更改数字格式:

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

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文