由于长数据类型导致的 VBA-Excel 溢出错误

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

VBA-Excel Overflow Error due to Long data type

vbaexcel-vbaexcel

提问by Krynce

This may seem too easy, but I am so desperate.

这似乎太容易了,但我很绝望。

What I need to do is get the last valueof the column "D" which has a

我需要做的是获取列“D”的最后一个值

big amount of number, ex. 987654321, the code is fine if the value is only two-digit. I just can't identify the problem.

大量的数字,例如。987654321,如果值只有两位数,代码就可以了。我只是无法确定问题所在。

Dim lastRow As Long
lastRow = Cells(Rows.Count, "D").End(xlUp).Value
Sheets("Sheet1").TxtBox1.Value = lastRow

回答by Siddharth Rout

Like I mentioned in my comment, for such large number you have to declare it as a double.

就像我在评论中提到的那样,对于如此大的数字,您必须将其声明为双倍。

Dim lastRow As Double

Alternatively since you want to store it in a textbox you can do 2 things

或者,由于您想将其存储在文本框中,您可以做两件事

  1. Declare it as a string
  2. Store it directly in the Textbox.

    Option Explicit
    
    Sub Sample1()
        Dim lastRow As String
    
        With Sheets("Sheet1")
            lastRow = .Cells(.Rows.Count, "D").End(xlUp).Value
            .TextBox1.Value = lastRow
        End With
    End Sub
    
    Sub Sample2()
        With Sheets("Sheet1")
            .TextBox1.Value = .Cells(.Rows.Count, "D").End(xlUp).Value
        End With
    End Sub
    
  1. 将其声明为字符串
  2. 将其直接存储在文本框中。

    Option Explicit
    
    Sub Sample1()
        Dim lastRow As String
    
        With Sheets("Sheet1")
            lastRow = .Cells(.Rows.Count, "D").End(xlUp).Value
            .TextBox1.Value = lastRow
        End With
    End Sub
    
    Sub Sample2()
        With Sheets("Sheet1")
            .TextBox1.Value = .Cells(.Rows.Count, "D").End(xlUp).Value
        End With
    End Sub
    

回答by Peter Albert

Long can only handle values up to 2.1B! For any larger values, better use Doubleinstead of Long

Long 只能处理高达 2.1B 的值!对于任何更大的值,更好地使用Double而不是Long