VBA Macro crashes after 32000 rows

calendar_today Asked May 11, 2012
thumb_up 21 upvotes
history Updated April 16, 2026

Question posted 2012 · +12 upvotes

I have a VBA macro that copies rows from one worksheet into another based upon finding values in cells in 3 columns. The macro works, but crashes when it reaches row 32767. There are no formulas or special formatting in this row. Further, I have taken that row out, but it still crashes on that row number. Is this a limitation in excel? There are some 43000 in the worksheet that is being process

Therefore, I ask what is wrong with my macro and how I can get it reach the end of the worksheet:

Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim wks As Worksheet
On Error GoTo Err_Execute

For Each wks In Worksheets

LSearchRow = 4
LCopyToRow = 4

ThisWorkbook.Worksheets.Add After:=Worksheets(Worksheets.Count)
Set wksCopyTo = ActiveSheet
wks.Rows(3).EntireRow.Copy wksCopyTo.Rows(3)

While Len(wks.Range("A" & CStr(LSearchRow)).Value) > 0

    If wks.Range("AB" & CStr(LSearchRow)).Value = "Yes" And wks.Range("AK" & CStr(LSearchRow)).Value = "Yes" And wks.Range("BB" & CStr(LSearchRow)).Value = "Y" Then

        Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
        Selection.Copy


        wksCopyTo.Select
        wksCopyTo.Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
        wksCopyTo.Paste

        'Move counter to next row
        LCopyToRow = LCopyToRow + 1
        'Go back to Sheet1 to continue searching
        wks.Select
    End If
    LSearchRow = LSearchRow + 1
Wend

Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Next wks
    Exit Sub
Err_Execute:
    MsgBox "An error occurred."

Please help!

Accepted answer +21 upvotes

The VBA ‘Int’ type is a signed 16-bit field so it can only hold values from -32768 to +32767. Change those variables to ‘Long’, which is a signed 32-bit field and can hold values from -2147483648 to +2147483647. Should be enough for Excel. 😉

Excel VBA objects referenced (5)

  • Application — Using events with the Application object
  • Application — Working with Other Applications
  • Range — Refer to Cells by Using a Range Object
  • Range — Delete Duplicate Entries in a Range
  • Selection — Working with the Selection Object

Top excel-vba Q&A (6)

+21 upvotes ranks this answer #18 out of 136 excel-vba solutions on this site — top 13%.