gpt4 book ai didi

excel - 为什么 Excel VBA 对我的整数除法结果进行四舍五入?

转载 作者:行者123 更新时间:2023-12-02 09:05:25 33 4
gpt4 key购买 nike

我正在 Excel 2002 中编写一个 VBA 宏来操作设备中的日期,该设备在 4 个 channel 中的每个 channel 上提供 10 个值。

当我尝试将一个整数除以另一个整数来计算行和列时,结果显示它正在使用银行家舍入,就好像它是浮点变量一样。

Sub TestRounding()
Dim Y As Integer
Dim Field As Integer
Dim Channel As Integer

ActiveWorkbook.Sheets.Add
ActiveWorkbook.ActiveSheet.Cells.Select
range("A1").Select

For Field = 1 To 40
Channel = (Field - 1) / 10
Y = Field - 1
ActiveSheet.range("A1").Offset(Y, Channel).Value = Field
Next Field

End Sub

Y 是放置输出的行,我通常用它来设置

Y = (Field -1) mod 10

但我把它保留为

Y = Field - 1

在生成的工作表中更清楚地说明这一点。

channel 应该是放置输出的列。

当我运行这个宏时,值1-6被放入A列,然后7-15被放入B列,16-26被放入C列,然后27-35被放入D列,然后36-40在 E 列中。

我期望值​​ 1-10 进入 A 列,11-20 进入 B 列,21-30 进入 C 列,31-40 进入 D 列。

我习惯了 C 和 C++,如果我将一个整数除以另一个整数,则会使用整数数学计算结果。 VBA 有什么不同?

最佳答案

要使用“整数数学”进行除法,请使用 \ 而不是 /

Integer Division \

Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division is used to get the fraction of one number in terms of another. The Visual Basic language provides two types of operations for the division. If you want the result of the operation to be a natural number, called an integer, use the backlash operator "\" as the divisor. The formula to use is: Value1 \ Value2 This operation can be performed on two types of valid numbers, with or without decimal parts. After the operation, the result would be a natural number.

Decimal Division /
The second type of division results in a decimal number. It is performed with the forward slash "/". Its formula is: Value1 / Value2 After the operation is performed, the result is a decimal number.

Source

关于excel - 为什么 Excel VBA 对我的整数除法结果进行四舍五入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16814018/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com