VBA Macro crashes after 32000 rows

后端 未结 3 1632
遇见更好的自我
遇见更好的自我 2020-11-27 08:06

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.

3条回答
  •  萌比男神i
    2020-11-27 08:27

    You can avoid the Integer vs. Long issue by using a For Each rather than incrementing rows. For Each is generally faster, as is avoiding Selecting Ranges. Here's an example:

    Sub CopySheets()
    
        Dim shSource As Worksheet
        Dim shDest As Worksheet
        Dim rCell As Range
        Dim aSheets() As Worksheet
        Dim lShtCnt As Long
        Dim i As Long
    
        Const sDESTPREFIX As String = "dest_"
    
        On Error GoTo Err_Execute
    
        For Each shSource In ThisWorkbook.Worksheets
            lShtCnt = lShtCnt + 1
            ReDim Preserve aSheets(1 To lShtCnt)
            Set aSheets(lShtCnt) = shSource
        Next shSource
    
        For i = LBound(aSheets) To UBound(aSheets)
            Set shSource = aSheets(i)
    
            'Add a new sheet
            With ThisWorkbook
                Set shDest = .Worksheets.Add(, .Worksheets(.Worksheets.Count))
                shDest.Name = sDESTPREFIX & shSource.Name
            End With
    
            'copy header row
            shSource.Rows(3).Copy shDest.Rows(3)
    
            'loop through the cells in column a
            For Each rCell In shSource.Range("A4", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
                If Not IsEmpty(rCell.Value) And _
                    rCell.Offset(0, 27).Value = "Yes" And _
                    rCell.Offset(0, 36).Value = "Yes" And _
                    rCell.Offset(0, 53).Value = "Yes" Then
    
                    'copy the row
                    rCell.EntireRow.Copy shDest.Range(rCell.Address).EntireRow
                End If
            Next rCell
        Next i
    
        MsgBox "All matching data has been copied."
    
    Err_Exit:
        'do this stuff even if an error occurs
        On Error Resume Next
        Application.CutCopyMode = False
        Exit Sub
    
    Err_Execute:
        MsgBox "An error occurred."
        Resume Err_Exit
    
    End Sub
    

提交回复
热议问题