Re: VBA Code: excel is hanging at some point
I have added two extra line in the code and this should work, please try.
Code
Sub Test()
Dim Rng As Range, A As Variant, e As Variant, sht As Worksheet, n As Long, i As Long
On Error Resume Next
Set sht = ThisWorkbook.Sheets("Dispatch_load")
If sht Is Nothing Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Dispatch_load"
End If
n = 10: i = 0
With Sheets("AMC Agent Breakout")
.Activate
For Each e In Array("KAX0", "KAX1", "KAX2", "KAX3", "KAX4", "KAX5", "KAX6", "KAX7", "KAX8", "KAX9")
.Range("A1:R" & .Range("A" & .Rows.Count).End(xlUp).Row).AutoFilter Field:=8, Criteria1:=e
.Range("A1:R" & .Range("A" & .Rows.Count).End(xlUp).Row).AutoFilter Field:=18, Criteria1:="0"
Set Rng = .AutoFilter.Range.Offset(1, 0).Resize(.AutoFilter.Range.Rows.Count - 1, .AutoFilter.Range.Columns.Count) _
.SpecialCells(xlCellTypeVisible)
If Not Rng Is Nothing Then
On Error Resume Next
Set sht = ThisWorkbook.Sheets("Agent&DRM")
If sht Is Nothing Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Agent&DRM"
End If
With Sheets("Agent&DRM")
.Activate
.UsedRange.Clear
' Added to clear the existing data
Rng.Copy .Range("C6")
.Columns("C:I").Delete Shift:=xlToLeft
.Columns("D:J").Delete Shift:=xlToLeft
.Columns("E:F").Delete Shift:=xlToLeft
.Range("T17").FormulaR1C1 = "AAX" & i
.Range("U17").FormulaR1C1 = "=SUM(R[-11]C[-17]:R[8983]C[-17])"
.Range("T17:U17").Copy
Sheets("Dispatch_load").Range("A" & n).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End With
n = n + 1: i = i + 1
End If
.AutoFilterMode = False
Set Rng = Nothing
' Newly added to release the memory
Next
End With
End Sub
Display More