title: runtime 1004 error when running vba code for second time
body: <p>I have written a small module to protect all the worksheets of my workbook and to protect certain ranges in certain sheets.</p>
  
  <p>The code runs smoothly the first time around, but when trying to run it for a second time I get a runtime 1004 error "Application-defined or object-defined error"</p>
  
  <p>I think I might have found some explanation on the following page:
  <a href="http://support.microsoft.com/kb/178510" rel="nofollow">http://support.microsoft.com/kb/178510</a>
  But I just can't figure it out..</p>
  
  <p>Could somebody please give me a hand ?</p>
  
  <p>My code is below.</p>
  
  <p>Depending on what sheet gets protected first, it is either this line</p>
  
  <pre><code>WS.Protection.AllowEditRanges.Add Title:=titlef _
          , Range:=WS.Range("L:R"), Password:="pw2"
  </code></pre>
  
  <p>or the following line that throws the erorr</p>
  
  <pre><code>WS.Protection.AllowEditRanges.Add Title:=titlec _
          , Range:=WS.Range("N:T"), Password:="pw3"
  
  Sub Protect()
  Dim WS As Worksheet
  Dim pWord As String
  pWord = "pw1"
  
  Dim aer As AllowEditRange
  For Each WS In Worksheets
      WS.Unprotect pWord
  For Each aer In WS.Protection.AllowEditRanges
      aer.Delete
  Next aer
  Next WS
  
  Dim counterf As Integer
  Dim counterc As Integer
  counterf = 1
  counterc = 1
  Dim titlef As String
  Dim titlec As String
  
  For Each WS In ActiveWorkbook.Worksheets
      WS.Protect Password:=pWord, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True
      WS.EnableSelection = xlNoRestrictions
      If InStr(UCase(WS.Name), "FORM") Then
          titlef = "Volumes form faits par poste" &amp; counterf
          WS.Unprotect pWord
          WS.Protection.AllowEditRanges.Add Title:=titlef _
          , Range:=WS.Range("L:R"), Password:="pw2"
          WS.Protect pWord
          counterf = counterf + 1
      ElseIf InStr(UCase(WS.Name), "COND") Then
          titlec = "Volumes cond faits par poste" &amp; counterc
          WS.Unprotect pWord
          WS.Protection.AllowEditRanges.Add Title:=titlec _
          , Range:=WS.Range("N:T"), Password:="pw3"
          WS.Protect pWord
          counterc = counterc + 1
      End If
  Next
  
  End Sub
  </code></pre>