• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Is there something in my code that would cause it to crash?

PipBoy808

Member
Hello!

I've been writing a macro to scan through column J within an array of data, identify certain entries and then place a header in a row above those entries.

Code:
Sub Headers ()
 
Dim lastRow As Long
Dim mycountry As String, newcountry As String
Dim c As Variant
mycountry = ""
Application.ScreenUpdating = False
With Worksheets("Weekly Planning")
  lastRow = .Cells(.Rows.Count, "J").End(xlUp).Row 'define the last row so xl knows how far to search through
 'MsgBox lastRow
  For Each c In Range(Cells(12, 10), Cells(lastRow, 10))
  newcountry = UCase(Right(c.Value, 3))
  If newcountry = "BE1" Then
  'New country detected!
  c.EntireRow.Insert
  .Cells(c.Row - 1, "B").Value = "HOLLAND".Cells(c.Row - 1, "B").RowHeight = 16
  .Cells(c.Row - 1, "B").WrapText = False
  .Cells(c.Row - 1, "B").Font.Bold = True
  End If
  Next c
End With
Application.ScreenUpdating = True
End Sub

When I run the code as above, it's fine. The problem starts when I add more conditions for different headers, e.g.:

Code:
Sub Headers ()
Dim lastRow As Long
Dim mycountry As String, newcountry As String
Dim c As Variant
mycountry = ""
Application.ScreenUpdating = False
With Worksheets("Weekly Planning")
  lastRow = .Cells(.Rows.Count, "J").End(xlUp).Row 'define the last row so xl knows how far to search through
 'MsgBox lastRow
  For Each c In Range(Cells(12, 10), Cells(lastRow, 10))
  newcountry = UCase(Right(c.Value, 3))
If newcountry = "BE1" Then
  'New country detected!
  c.EntireRow.Insert
  .Cells(c.Row - 1, "B").Value = "HOLLAND".Cells(c.Row - 1, "B").RowHeight = 16
  .Cells(c.Row - 1, "B").WrapText = False
  .Cells(c.Row - 1, "B").Font.Bold = True
ElseIf newcountry = "BN1" Then
  'New country detected!
  c.EntireRow.Insert
  .Cells(c.Row - 1, "B").Value = "GERMANY".Cells(c.Row - 1, "B").RowHeight = 16
  .Cells(c.Row - 1, "B").WrapText = False
  .Cells(c.Row - 1, "B").Font.Bold = True
    End If
  Next c
End With
Application.ScreenUpdating = True
End Sub

In the above form, the code causes Excel to crash, both on a brand new machine with 8GB of RAM and an i7 processor and also on a remote connection to a server with 128GB of RAM. Have I done something that inherently might cause Excel to crash, like a circular reference or something?
 
Hi, PipBoy808!
Tried debugging the code line by line with F8? So you'll find out in what line it's crashing, which will be helpful.
Regards!
 
Back
Top