Excel VBA中可以允许整数溢出吗?

很简单,但我找不到任何通过谷歌search。 我想要发生的一个例子:

Function myFunc() Dim a As Integer Dim b As Integer Dim c As Integer a = 20000 b = 15000 c = a + b myFunc = c End Function 

我希望myFunc()返回-30536,而不是抛出一个溢出exception。 我知道我可以写一个这样做的函数,但是我已经为一个项目编写了一堆代码,假设溢出是允许的,所以我希望有一个快速的修复。

编辑:我不需要帮助来解决types转换溢出问题的function。 我已经有一个; 我只想避免改变数百个加减运算。 我也有点沮丧,VBA似乎走出了禁用溢出function的方式 – 它应该让用户决定是否要使用它。

我会build议编写MyFunc做Long的math,并testing整数“溢出”,并进行调整

 Function MyFunc(a As Integer, b As Integer) As Integer Dim sum As Long Const Mask As Integer = -1 sum = CLng(a) + CLng(b) If sum > 32767 Then sum = sum - 65536 ElseIf sum < -32768 Then sum = sum + 65536 End If MyFunc = sum End Function 

用testing

 Sub zx() Debug.Print MyFunc(20000, 15000) End Sub 

为了防止Excel VBA代码中的Integer溢出,您可以使用自定义Function执行IntegerLong型转换,如下所示:

 Sub TestIntegerConversion() Debug.Print myFuncLong(20000, 15000) End Sub Function myFuncLong(a As Integer, b As Integer) As Long myFuncLong = CLng(a) + CLng(b) End Function 

或者不使用自定义函数,就像这样:

 Sub PreventOverflow() Dim a As Integer Dim b As Integer a = 20000 b = 15000 Debug.Print CLng(a) + CLng(b) End Sub 

或者,你可以编写自己的自定义函数,它应该实现“溢出math”(你有某种方式指定使用普通的math符号如何从35000获得数字-30536)并返回结果作为Long ,或String 。 可能的实现如下所示(注:溢出例外数为6)

 Sub OverflowCustomMath() Dim a As Integer Dim b As Integer Dim c As Long a = 20000 b = 15000 On Error GoTo Err: Debug.Print a + b Err: If (Err.Number = 6) Then 'apply your custom overflow math, as for eg Debug.Print CLng(a) + CLng(b) End If End Sub 

希望这可能有帮助。

使用典型的VBAerror handling程序,但testing你的情况。

  Option Explicit Sub test() MsgBox myFunc End Sub Function myFunc() On Error GoTo Local_err Dim a As Integer Dim b As Integer Dim c As Integer a = 20000 b = 15000 c = a + b myFunc = c Local_exit: Exit Function Local_err: If Err = 6 Then myFunc = -30536 Else MsgBox Err & " " & Err.Description ' myFunc = whatever error value to return End If Resume Local_exit End Function