传递给数组时四舍五入的 Excel VBA 单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14323971/
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
Excel VBA Cell value rounded when passed to an array
提问by Dan Ricketts
I'm hoping this has a simple solution. I need to take values in from a worksheet, perform calculations and insert them into a hidden worksheet (to be uploaded later into a database). I don't normally program in VBA, so I'm not sure what I'm doing wrong. My problem is this: when I copy data from the worksheet into the array, they are rounded like an integer when I've specified long. The following code snippet will give you an idea of the problem. Am I initializing the array wrong?
我希望这有一个简单的解决方案。我需要从工作表中获取值,执行计算并将它们插入到隐藏的工作表中(稍后上传到数据库中)。我通常不使用 VBA 编程,所以我不确定我做错了什么。我的问题是:当我将工作表中的数据复制到数组中时,当我指定 long 时,它们会像整数一样四舍五入。以下代码片段将让您了解问题所在。我初始化数组错了吗?
Dim ThisWS As Worksheet
Set ThisWS = Excel.ActiveWorkbook.Worksheets("BchSheet")
Dim BTW() As Long 'Beaker Tare Weight
ReDim Preserve BTW(Samples)
BTW(1) = ThisWS.Cells(18, 6).Value 'Value in cell is 98.7036
MsgBox (ThisWS.Cells(18, 6).Value) 'Returns 98.7036
MsgBox (BTW(1)) 'Returns 99
回答by LittleBobbyTables - Au Revtheitroad
The Long
data type, like Integer
, only holds whole numbers.
该Long
数据类型一样Integer
,仅持有整数。
Use the Double
data type to store decimals, or the Currency
data type if you are working with calculations where fixed-point is necessary or you don't want to deal with floating-point numbers.
使用Double
数据类型来存储小数,或者Currency
如果您正在处理需要定点或不想处理浮点数的计算,则使用数据类型。