Getting 1004 error on code that worked after adding new code

43 views Asked by At

I'm stumped (doesn't take much). I have two bits of code that don't seem to work well together. I would like them to or find an alternative. The first is a command button code that clears contents and changes formatting. This worked perfectly fine until I added "if value changes" code. The value change code refers to cells in the range where the formatting is changing from the first code. I imagine this is the issue. The codes use named ranges for the most part. I have attempted to use cell addresses, defining range in code, protect/unprotect, and adding the sheet name to the range.

This code works just fine without the "if value changes" code.

Private Sub CommandButton2_Click()
    Sheets("PN Generation").unprotect Password:="1234"
    Range("SELECT").Value = 2
    Range("PNSELECT").ClearContents
    Range("SMC").ClearContents
    Range("ALL").Interior.ColorIndex = 35
    Range("ALL").Font.ColorIndex = 49
    Range("SMC").Interior.ColorIndex = 6
    Range("SMCD").Font.ColorIndex = 15
    Range("SMCD").Interior.ColorIndex = 15
    Call protect

End Sub

When using the below code, the above code returns an 1004 Application defined/Object defined error starting at line 5 - "Range("ALL").Interior.ColorIndex=35."

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D3")) Is Nothing Then
    
            If Range("PNI") = "G" Or Range("PNI") = "U" Or Range("PNI") = "L" Or Range("PNI") = "T" Then
            Sheets("Reverse Build").Range("MV").Copy
            Sheets("PN Generation").Range("PFLMV").PasteSpecial xlPasteValues
        End If
        
        If Range("PNI") = "A" Or Range("PNI") = "B" Or Range("PNI") = "C" Or Range("PNI") = "V" Or Range("PNI") = "AR" Then
            Range("LV").Copy
            Range("PF").PasteSpecial xlPasteValues
        End If
        
        If Range("PNI") = "S" Or Range("PNI") = "P" Then
            Range("SIN").Copy
            Range("PF").PasteSpecial xlPasteValues
        End If
        
        If Range("PNI") = "F" Then
            Range("BARE").Copy
            Range("PF").PasteSpecial xlPasteValues
        End If
        
        If Range("PNI") = "R" Then
            Range("LVU").Copy
            Range("PF").PasteSpecial xlPasteValues
        End If
       End Sub

I'd like to understand why I'm getting the error and how to fix prevent the error.

1

There are 1 answers

0
Sean On

Application.EnableEvents = False... Application.EnableEvents = True worked.

Thank you BigBen. You should know, you just helped a Bengals fan. lol