Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA-Excel Overflow Error due to Long data type

Tags:

excel

vba

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

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

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

Dim lastRow As Long
lastRow = Cells(Rows.Count, "D").End(xlUp).Value
Sheets("Sheet1").TxtBox1.Value = lastRow
like image 600
Krynce Avatar asked Mar 22 '13 08:03

Krynce


People also ask

How do I fix the overflow error in Excel VBA?

The data type Byte can hold values from 0 to 255. So it causes an error. To fix the error, we either change the data type or reduce the value assigned to the variable “Number.”

What causes overflow error in VBA?

In VBA, Overflow (Error 6) is a run-time error that occurs when you specify a number to the variable that is out of the range of numbers which that data type can take. In simple words, this error occurs when you go out of the range for a variable's type.

What is long data type in VBA?

What is a Long Data Type in VBA? Long is a data type in VBA used to store the numeric values. We know that integer also holds numeric values, but Long differs from integers as the data storage range is very big. In the case of the Long data type, we can hold decimal values too. So, it is a built-in data type.

How do you handle overflow in VBA?

How to fix an overflow error in VBA - Quora. By far the most common cause of an overflow error in VBA is using an Integer variable type for a row number exceeding 32,767. Integer variables have only 16 bits, and so are limited to the range ±32,767. To avoid such problems, use the Long variable type instead.


1 Answers

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
    
like image 84
Siddharth Rout Avatar answered Sep 17 '22 23:09

Siddharth Rout