2015-10-15 50 views
0

嘗試清除單元格內容並重置其各自顏色時出現運行時錯誤1004。我首先解除工作表的保護,然後嘗試清除單元格內容並重置單元格顏色,但excel引發異常。任何意見非常感謝。應用程序定義的或對象定義的錯誤(運行時錯誤1004)

Sub ClearField() 



    Dim ws As Worksheet 
    Dim pw As String 

    pw = "xxxxxxxxxxxx" 

    Set ws = ActiveSheet 

    With ws 
     'unprotect sheet 
     .Unprotect pw 



     Range("O3:R3").Select 
     Selection.ClearContents 
     Range("O3:R3").Interior.Color = RGB(255, 255, 255) 


     Range("X3:AC3").Interior.Color = RGB(255, 255, 255) 
     Range("X3:AC3").Select 
     Selection.ClearContents 



     Range("AE3:AJ3").Interior.Color = RGB(255, 255, 255) 
     Range("AE3:AJ3").Select 
     Selection.ClearContents 



     Range("AL3").Interior.Color = RGB(255, 255, 255) 
     Range("AL3").Select 
     Selection.ClearContents 



     Range("A7:AI36").Select 
     Range("A7:AI36").Interior.Color = RGB(255, 255, 255) 
     Range("AI7").Activate 
     Selection.ClearContents 



     Range("J39:V40").Interior.Color = RGB(255, 255, 255) 
     Range("J39:V40").Select 
     Selection.ClearContents 



     Range("AD44:AL45").Interior.Color = RGB(255, 255, 255) 
     Range("AD44:AL45").Select 
     Selection.ClearContents 



     Range("AX3:AY3").Interior.Color = RGB(255, 255, 255) 
     Range("AX3:AY3").Select 
     Selection.ClearContents 



     Range("AU7:AU36").Interior.Color = RGB(255, 255, 255) 
     Range("AU7:AU36").Select 
     Selection.ClearContents 




     Range("AZ7:BC36").Interior.Color = RGB(255, 255, 255) 
     Range("AZ7:BC36").Select 
     Selection.ClearContents 



     Range("BF7:BP36").Interior.Color = RGB(255, 255, 255) 
     Range("BF7:BP36").Select 
     Selection.ClearContents 


     Range("E6").Select 


     Range("AN46:AW51").Interior.Color = RGB(255, 255, 255) 
     Range("AN46:AW51").Select 
     Selection.ClearContents 

     'protect worksheet 
     .Protect pw 
    End With 



End Sub 
+0

這已經有了答案? – Davesexcel

回答

1

需要判定所有Range(...)引用您解除一樣的工作方式和保護,具有.。您也可以刪除所有select語句,並按照我在下面顯示的方式操作您的範圍。

Sub ClearField() 

Dim ws As Worksheet 
Dim pw As String 

pw = "xxxxxxxxxxxx" 

Set ws = ActiveSheet 

    With ws 
     'unprotect sheet 
     .Unprotect pw 

     With .Range("O3:R3") 
      .ClearContents 
      .Interior.Color = RGB(255, 255, 255) 
     End With 

     ' ... rewrite the rest in the way I have done above 

     'protect worksheet 
     .Protect pw 

    End With 

End Sub 
1

保持它在一起是一種方法以及

Dim ws As Worksheet, rng As Range 
Dim pw As String 
pw = "xxxxxxxxxxxx" 
Set ws = ActiveSheet 
With ws 
    .Unprotect pw 'unprotect sheet 
    Set rng = .Range("O3:R3,X3:AC3,AE3:AJ3,AL3,A7:AI36,J39:V40,AD44:AL45,AX3:AY3,AU7:AU36,AZ7:BC36,BF7:BP36,AN46:AW51") 
    rng.Interior.Color = RGB(255, 255, 255) 
    rng.ClearContents 
    .Protect pw 
End With 
相關問題