简体   繁体   中英

How do I fix error 1004 in vba excel when trying to unlock some cells?

I know that there are already a bunch of threads on error 1004, but after digging through them I haven't found a situation similar to mine. I'm trying to lock a workbook except for a range of cells, using the info I found here and the following code:

If SecurityActive= "yes" Then
    Worksheets("Invullen").Range("D7, D9, D11, D15, D17, D19, D23, J12, J14:J16").Locked = False

    'INVULLEN
    Worksheets("Invullen").Protect UserInterfaceOnly:=True
    'AFDRUKKEN
    Worksheets("Afdrukken").Protect UserInterfaceOnly:=True
    'AFDRUKKENBEFR
    Worksheets("AfdrukkenBEfr").Protect UserInterfaceOnly:=True
    'BENL
    Worksheets("BEnl").Protect UserInterfaceOnly:=True
    'BEFR
    Worksheets("BEfr").Protect UserInterfaceOnly:=True
    'NL
    Worksheets("NL").Protect UserInterfaceOnly:=True
    'FR
    Worksheets("FR").Protect UserInterfaceOnly:=True
    'UK
    Worksheets("UK").Protect UserInterfaceOnly:=True
    'DE
    Worksheets("DE").Protect UserInterfaceOnly:=True
    'TECHNISCH
    Worksheets("Technisch").Protect UserInterfaceOnly:=True

End If

SecurityActive is a variable I use to be able to quickly change wether I want to secure the workbook or not. The error highlights the second line of the code. Does anyone how to fix the error?

Runtime 1004 will be thrown while trying to alter cell properties while the sheet is still protected.

Use:

Worksheets("Invullen").Unprotect
Worksheets("Invullen").Range("D7, D9, D11, D15, D17, D19, D23, J12, J14:J16").Locked = False
'... Other stuff
Worksheets("Invullen").Protect UserInterfaceOnly:=True

etc.

Since Excel 2016 the runtime error 1004 is more specific than until 2010. With protection on it'll throw "1004 Unable to set the Locked property of the Range class."

Edit: This error also get's thrown when one or more cells in the address range are merged cells.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM