vba VBA项目中的整数溢出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2669166/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:34:08  来源:igfitidea点击:

Integer Overflow in VBA project

vbaoverflowexcel-vbaexcel

提问by mcoolbeth

everyone. Here is a small VBA (Excel) function that i wrote, full of MsgBoxes for debugging.

每个人。这是我编写的一个小型 VBA (Excel) 函数,其中包含用于调试的 MsgBoxes。

I am passing in the numbers 10 and 1 as arguments, and getting an overflow error when the program reaches the top of the For loop, before it begins the first iteration.

我将数字 10 和 1 作为参数传递,并在程序开始第一次迭代之前到达 For 循环的顶部时收到溢出错误。

Any thoughts are appreciated.

任何想法表示赞赏。

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Function PerformanceTest(iterations As Integer, interval As Integer) As Double
    Dim st, tot, k As Double
    Dim n As Integer
    tot = 0#
    MsgBox "ok"
    k = iterations + tot
    MsgBox "ookk"
    n = 1
    MsgBox "assigned"
    For n = 1 To iterations
        MsgBox n
        st = Timer
        Application.Calculate
        tot = tot + (Timer - st)
        Sleep (1000 * interval)
    Next n
    'MsgBox (tot / k)
    PerformancTest = tot / k
End Function

回答by Tomalak

Redundancy removed, the essentially unchanged function runs without error in my Excel 2003

删除了冗余,基本不变的函数在我的 Excel 2003 中运行没有错误

Function PerformanceTest(iterations As Integer, interval As Integer) As Double
  Dim st, tot As Double
  Dim n As Integer

  For n = 1 To iterations
    st = Timer
    Application.Calculate
    tot = tot + Timer - st
    ''# Sleep (1000 * interval)
  Next n

  PerformanceTest = tot / (iterations + tot)
End Function

So… the error you see is probably not within the function itself.

所以……您看到的错误可能不在函数本身之内。

P.S.: Pro tip: ;-) Use Debug.Printinstead of MsgBoxfor debug output.

PS:专业提示:;-) 用于Debug.Print代替MsgBox调试输出。

回答by Smandoli

At the risk of looking like a fool again, here's some input.

冒着再次看起来像个傻瓜的风险,这里有一些输入。

I would build my timer function like this. It seems simpler to me. (Not counting that I deleted some unessential lines -- I mean it's structurally simple.)

我会像这样构建我的计时器功能。对我来说似乎更简单。(不算我删除了一些不重要的行——我的意思是它在结构上很简单。)

And if it ran without overflow, well that would be a nice plus.

如果它在没有溢出的情况下运行,那将是一个不错的加分项。

Function PerformanceTest(iterations As Integer, interval As Integer) As Double

Dim st, tot, k As Double
Dim n As Integer

PerformanceTest = Timer
k = iterations + tot
n = 1

For n = 1 To iterations
    '' insert operation that takes time
    Sleep (1000 * interval)
Next n

PerformanceTest = Timer - PerformanceTest
PerformanceTest = PerformanceTest / k
End Function