Yes, the Long variable type in Excel VBA stores whole numbers from -2,147,483,648 to 2,147,483,647, and you declare it with Dim variableName As Long. It is the default integer type in modern VBA because it handles larger values and avoids the overflow errors that plague the older Integer type. This guide shows you exactly how to declare, assign, and work with Long variables, plus how to fix the most common pitfalls.
What You'll Need
- Microsoft Excel (any version that supports VBA, which is all desktop versions).
- Access to the Visual Basic Editor: press
Alt+F11in Excel. - A basic understanding of what a variable is (a named container for data).
Step-by-Step
- Open the VBA editor. Press
Alt+F11in Excel. If you don't see the Project Explorer on the left, go toView > Project Explorer. - Insert a module. In the Project Explorer, right-click any workbook name (like
VBAProject (Book1)), chooseInsert, thenModule. This gives you a clean sheet to type code. - Declare a Long variable. Type
Dim rowCount As Longat the top of the module or inside a procedure. This tells VBA to reserve memory for a whole number that can go up to about 2.1 billion. - Assign a value. Use the variable in code, for example:
rowCount = 1048576(the number of rows in an Excel worksheet). You can also assign the result of a function:rowCount = WorksheetFunction.CountA(Range("A:A")). - Use it in a loop. A common use is a loop that goes through many rows. For example:
UsingDim i As Long For i = 1 To 1000000 ' do something Next iLonghere prevents an overflow error if you ever increase the loop limit beyond 32,767. - Use it with the Rows.Count property. Instead of hardcoding numbers, use Excel's own counts. For example, to loop through all rows in a sheet:
This is a classic pattern that requiresDim lastRow As Long lastRow = Cells(Rows.Count, 1).End(xlUp).RowLongbecauseRows.Countreturns aLong(1048576 in modern Excel). - Convert other types to Long. If you have a string that contains a number, use
CLngto convert it:Dim n As Long: n = CLng("12345"). If the string is not a number, VBA will throw a type mismatch error. - Declare multiple Longs on one line. You can write
Dim a As Long, b As Long, c As Longto save space. Note thatDim a, b, c As Longonly makesca Long;aandbbecome Variant. Always specifyAs Longfor each variable.
Common Mistakes
- Using Integer instead of Long. The
Integertype only goes up to 32,767. If you try to assign 40,000 to an Integer, you get an overflow error. Always useLongunless you have a specific reason to useInteger(like working with a legacy API). - Forgetting to declare the variable. If you don't use
Dim, VBA creates a Variant, which is slower and can cause subtle bugs. AddOption Explicitat the top of your module to force declaration. - Assigning a decimal number to a Long.
Longonly stores whole numbers. If you assign3.7, VBA rounds it to4(banker's rounding). If you need decimals, useDoubleorSingle. - Using Long for text or dates.
Longis for numbers. For text useString, for dates useDate. Using the wrong type causes type mismatch errors. - Not accounting for negative numbers.
Longcan hold negative values, so it's fine, but if you useLongto store a row number that should never be negative, add a check likeIf rowCount < 1 Then Exit Sub.
Tips
- Use Long for all loop counters. Even if your loop is small, it's a good habit. It costs no extra memory and prevents overflow if you later change the loop limit.
- Use Long for array indices. If you declare an array with
Dim arr(1 To 1000000) As Long, the index variable should beLong. - Use the
TypeNamefunction to debug. If you're unsure what type a variable is, useMsgBox TypeName(variableName)to see it. - Use
CLngto avoid rounding surprises. When converting from a floating-point number,CLngrounds to the nearest even number (e.g.,CLng(2.5)returns 2,CLng(3.5)returns 4). If you want standard rounding, useRoundfirst. - Use
LongLongfor 64-bit values. If you're on 64-bit Office and need numbers beyond 2.1 billion, useLongLong(range: -9.2 quintillion to 9.2 quintillion). Declare it asDim big As LongLong.
Troubleshooting
Overflow error (Error 6): This happens when you try to assign a number too large for the variable type. Check the value you're assigning. If it's a calculation, the result might exceed 2,147,483,647. For example, Dim x As Long: x = 3000000 * 3000000 overflows because the product is 9e12. Fix: use Double for intermediate calculations, or use LongLong if you're on 64-bit.
Type mismatch error (Error 13): You're trying to assign a non-numeric value to a Long. For example, Dim x As Long: x = "abc" gives this error. Use CLng only when the string is a valid number. If you're reading from a cell and it might contain text, use IsNumeric to check first.
Variable not declared: If you get a "Variable not defined" error, you likely have Option Explicit and haven't declared the variable. Go to the top of the module and add Dim variableName As Long.
Wrong result due to rounding: If you assign a decimal to a Long and get an unexpected number, remember that VBA rounds to the nearest even integer. Use Round with a specified number of decimal places if you need consistent rounding.
Loop runs slowly: If you're using a Long in a loop that runs millions of times, it's fine. But if the loop is slow, it's not because of the Long type; it's because of what you're doing inside the loop. Consider turning off screen updating with Application.ScreenUpdating = False at the start and re-enabling it at the end.
Frequently Asked Questions
Why should I use Long instead of Integer?
Because Integer can only hold values up to 32,767. Any larger value causes an overflow error. Long handles up to 2.1 billion, which covers row counts, file sizes, and most counting tasks. It also avoids the performance penalty of VBA converting between Integer and Long internally.
Can I use Long to store a decimal number?
No, Long only stores whole numbers. If you assign a decimal, VBA rounds it to the nearest even integer. For decimals, use Double or Single.
What is the maximum value of a Long variable?
2,147,483,647 (about 2.1 billion). The minimum is -2,147,483,648. If you need larger, use LongLong on 64-bit Office.
How do I convert a string to a Long?
Use CLng(string). For example, Dim n As Long: n = CLng("123"). If the string isn't a valid number, VBA raises a type mismatch error.
What is the difference between Long and LongLong?
Long is 32-bit, LongLong is 64-bit. LongLong can store numbers up to about 9.2 quintillion. It's only available in 64-bit versions of Office. If you're on 32-bit, LongLong is not available.
Does using Long slow down my code?
No, Long is actually faster than Integer in VBA because VBA internally converts Integer to Long for arithmetic. Using Long avoids that conversion. It also uses the same memory as Integer (4 bytes vs 2 bytes), but the speed benefit outweighs the tiny memory increase.