使用Excel获取错误6溢出。通常情况下,这是由于一个应该是很长的整数。但是这个..。我只是想把三个数字相乘,然后把结果放在一个细胞里。没有任何变数。
这是它的错误行: wsResults.Cells(4,3).Value = (60 * 60 * 24)
我试着关闭Excel并重新打开工作簿,并尝试将公式直接放入公式栏(它正确显示),但是VBA代码仍然无法工作。
有人有什么想法吗?谢谢!
Option Explicit
'Worsheets:
Dim wbThis As ThisWorkbook
Dim wsResults As Worksheet
'Set Timekeeping Values:
Public Const GameTick As Single = (60 / 12) / 4
Public Const GameRound As Single = GameTick * 12
Public Const GameHour As Single = GameRound * 60
Public Const GameDay As Single = GameHour * 24
Public Const GameWeek As Single = GameDay * 7
Public Const GameMonth As Single = GameDay * 30
Public Const GameYear As Single = GameDay * 365
Public Sub TimeControl()
'Initialize Timer:
Randomize Timer
'Set Worksheets:
Set wbThis = ThisWorkbook
Set wsResults = wbThis.Sheets("Results")
'Clear wsResults:
wsResults.Range("A1:M1000").ClearContents
'Display Unit Names:
wsResults.Cells(1, 1).Value = "Tick"
wsResults.Cells(2, 1).Value = "Round"
wsResults.Cells(3, 1).Value = "Hour"
wsResults.Cells(4, 1).Value = "Day"
wsResults.Cells(5, 1).Value = "Week"
wsResults.Cells(6, 1).Value = "Month"
wsResults.Cells(7, 1).Value = "Year"
'Display Game Units:
wsResults.Cells(1, 2).Value = GameTick
wsResults.Cells(2, 2).Value = GameRound
wsResults.Cells(3, 2).Value = GameHour
wsResults.Cells(4, 2).Value = GameDay
wsResults.Cells(5, 2).Value = GameWeek
wsResults.Cells(6, 2).Value = GameMonth
wsResults.Cells(7, 2).Value = GameYear
'Display Real-World Units:
wsResults.Cells(1, 3).Value = ""
wsResults.Cells(2, 3).Value = 60
wsResults.Cells(3, 3).Value = (60 * 60)
wsResults.Cells(4, 3).Value = (60 * 60 * 24)
wsResults.Cells(5, 3).Value = (60 * 60 * 24 * 7)
wsResults.Cells(6, 3).Value = (60 * 60 * 24 * 30)
wsResults.Cells(7, 3).Value = (60 * 60 * 24 * 365)
End Sub发布于 2016-11-22 05:07:39
规范
当您试图进行超出分配目标限制的分配时,会出现溢出。此错误有以下原因和解决方案:
确保您的赋值符合所分配的属性的范围。您尝试在计算中使用一个数字,该数字被强制为整数,但结果大于整数。
例如:
长x= 2000 * 365‘错误:溢出
要解决这种情况,输入数字,如下所示:
长x=CLng(2000年)* 365
在您的例子中,尝试使用以下方法
wsResults.Cells(4,3).Value = CLng(60 * 60) * 24 wsResults.Cells(5,3).Value = CLng(60 * 60) * 24 *7 wsResults.Cells(6,3).Value = CLng(60 * 60) * 24 * 30
编辑
为什么需要这种转换?
60、60和24都是整数值。在VBA中,整数是16位有符号类型,当对两个整数执行算术时,算法是以16位执行的。由于将这两个数字相乘的结果超过了可以用16位表示的值,因此将得到一个异常。
第二个示例(与CLng的转换)工作,因为第一个数字首先被转换成32位类型,然后使用32位数字执行算法。
在您的示例中,算法是用16位整数执行的,然后将结果转换为long,但此时已经太晚了,溢出已经发生。解决方案是首先将乘法中的一个操作数转换为长操作数。
https://stackoverflow.com/questions/40733883
复制相似问题