将变量相除会得出错误的零结果

时间:2018-08-29 01:59:05

标签: excel vba

我有一些代码正在从用户表单中获取一些输入,然后将其输入到我的电子表格中,这并不麻烦。问题是我的数据有2个,这是除以2个其他变量的结果,无论给出的真实答案是什么,总是给出零的结果。但是,如果我进入电子表格本身并使用相同的输入进行计算,则它完全可以按照我的需要工作。引起我悲伤的变量是“ rRate”和“ pRate”。我的变量声明有问题吗?还是完全没有其他问题?

Dim rRate As Long
Dim sTime As Date
Dim fTime As Date
Dim tTime As Date
Dim pRate As Long
Dim Rejects As Long
Dim tProd As Long

Rejects = frmProduction.lblTotalRejects.Caption
tProd = frmProduction.lblTotal.Caption

rRate = Rejects / tProd 'msgbox gives 0

sTime = ThisWorkbook.ActiveSheet.Cells(lRow, "B")
fTime = Now
tTime = fTime - sTime

pRate = tTime / tProd 'msgbox gives 0

ThisWorkbook.ActiveSheet.Cells(lRow, "O") = Rejects
ThisWorkbook.ActiveSheet.Cells(lRow, "P") = tProd
ThisWorkbook.ActiveSheet.Cells(lRow, "AH") = Format(rRate, Percent) 'not working
ThisWorkbook.ActiveSheet.Cells(lRow, "AI") = Format(tTime, "h:mm")
ThisWorkbook.ActiveSheet.Cells(lRow, "AL") = Format(pRate, "h:mm:ss") 'not working

2 个答案:

答案 0 :(得分:3)

您猜到,问题出在变量声明上。

rRatepRate都是除法的结果:rRate = Rejects / tProdpRate = tTime / tProd。由于将变量声明为As Long,因此结果的所有小数位将被静默丢弃。

例如,如果您期望rRate为0.475,如果声明为As Long,则小数位将被丢弃,它等于0,而您的msgBox将返回0。相反,您可以将它们声明为As Double

有关更多详细信息,请参见LongDouble数据类型。

答案 1 :(得分:1)

为了结束这个问题,这里是现在可以运行的代码。感谢BigBen的投入。

Dim rRate As Double
Dim sTime As Date
Dim fTime As Date
Dim tTime As Date
Dim pRate As Double
Dim Rejects As Long
Dim tProd As Long

Rejects = frmProduction.lblTotalRejects.Caption
tProd = frmProduction.lblTotal.Caption

rRate = Rejects / tProd

sTime = ThisWorkbook.ActiveSheet.Cells(lRow, "B")
fTime = Now
tTime = fTime - sTime

pRate = tTime / tProd

ThisWorkbook.ActiveSheet.Cells(lRow, "AH") = Format(rRate, Percent)
ThisWorkbook.ActiveSheet.Cells(lRow, "AL") = Format(pRate, "h:mm:ss")