此计算中的小数位于何处?

时间:2017-02-21 19:38:26

标签: excel-vba vba excel

我有一个计算BOL编号的函数,只取前10位数。

这是代码。

Public Function GENERATEBOLNUMBER(iYearSuffix As Integer, _
                              sFromZipcode As String, _
                              sToZipCode As String, _
                              iWeight As Integer, _
                              iShowID As Integer) As String

    Application.ScreenUpdating = False

    GENERATEBOLNUMBER = VBA.Left(7 & _
    WorksheetFunction.RoundUp(VBA.Right(sFromZipcode, 5) _
    * VBA.Right(sToZipCode, 5) * iWeight * (iShowID + 1234), 0), 10)

    Application.ScreenUpdating = True
End Function

以下是我传递的价值观。 7表示iYearSuffix,78224表示sFromZipcode,78224表示sToZipCode,410表示iWeight,1表示iShowID。所有这一切都计算到3098352701017600,所以最后的字符串应该是7309835270,这是包括在内的第一个数字和后面的9个数字。

小数来自哪里?我得到的答案是:73.0983527。

1 个答案:

答案 0 :(得分:2)

您正在混合字符串处理,数字操作,字符串和数字之间的隐式转换,VBA,WorksheetFunction和巨大的数字。什么可能出错?

如果您要在VBA中编写UDF,请在VBA中编写。唯一足以存储结果的数据类型将是Decimal,因此您必须将其声明为Variant,并明确强制执行计算以强制它强制执行:< / p>

Public Function GENERATEBOLNUMBER(yearSuffix As Integer, fromZip As String, _
                                  toZip As String, weight As Integer, _
                                  showId As Integer) As String
    Dim result As Variant
    'Calculate intermediary result.
    result = CDec(Right$(fromZip, 5)) * CDec(Right$(toZip, 5)) * weight * (showId + 1234)
    'Shift the decimal place 7 places to the left:
    result = result / 10 ^ 7
    'Skip the RoundUp call - it wasn't doing anything because your result was an integer.
    'Strip the non-integer portion:
    result = Fix(result)
    'Cast to a string an concatenate the "7" onto the start:
    GENERATEBOLNUMBER = "7" & CStr(result)
End Function