应用程序定义或对象定义的错误(运行时错误1004)

时间:2015-10-15 14:34:53

标签: vba excel-vba excel

尝试清除单元格内容并重置各自的颜色时,我得到运行时错误1004。我先取消保护工作表,然后尝试清除单元格内容并重置单元格颜色,但excel会抛出异常。任何建议都非常感谢。

    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

2 个答案:

答案 0 :(得分:1)

您需要使用与Range(...)相同的方式对所有.引用进行限定,方法与使用unprotect和protect一样。您也可以删除所有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 :(得分: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