Overflow Error in Excel VBA with Type Double

后端 未结 1 1776
有刺的猬
有刺的猬 2021-01-19 14:33

I have run into an overflow error in Excel VBA and cannot find my way around it. While Microsoft\'s documentation indicates that the range for doubles should reach ~1.8E308,

相关标签:
1条回答
  • 2021-01-19 14:44

    Try using Chip Pearson's XMod function:

    x(i) = XMod((CDbl(48271) * seed), CDbl(2 ^ 31 - 1))
    

    As he notes:

    You can also get overflow errors in VBA using the Mod operator with very large numbers. For example,

    Dim Number As Double
    Dim Divisor As Double
    Dim Result As Double
    
    Number = 2 ^ 31
    Divisor = 7
    Result = Number Mod Divisor ' Overflow error here.
    

    Code for the function:

    Function XMod(ByVal Number As Double, ByVal Divisor As Double) As Double
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' XMod
    ' Performs the same function as Mod but will not overflow
    ' with very large numbers. Both Mod and integer division ( \ )
    ' will overflow with very large numbers. XMod will not.
    ' Existing code like:
    '       Result = Number Mod Divisor
    ' should be changed to:
    '       Result = XMod(Number, Divisor)
    ' Input values that are not integers are truncated to integers. Negative
    ' numbers are converted to postive numbers.
    ' This can be used in VBA code and can be called directly from 
    ' a worksheet cell.
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Number = Int(Abs(Number))
        Divisor = Int(Abs(Divisor))
        XMod = Number - (Int(Number / Divisor) * Divisor)
    End Function
    

    Additional details:

    http://www.cpearson.com/excel/ModFunction.aspx

    0 讨论(0)
提交回复
热议问题