If-Then-Else代码locking/解锁单元格保持失败

使用:Excel 2010

我的代码的这部分保持失败,我不知道为什么。 当我尝试运行整个代码块时,它将返回“运行时错误”1004“:无法设置Range类的Locked属性”。

'Lock/unlock issue ThisWorkbook.Sheets("Dashboard").Activate ActiveSheet.Unprotect Password:="my password" Selection.Locked = False Selection.FormulaHidden = False If Range("D20").Value <> "Document Recorded" Then Range("F24").Locked = True Else Range("F24").Locked = False ActiveSheet.Protect Password:="my password", DrawingObjects:=True, Contents:=True, Scenarios:=True 

基本上,我想说:如果单元格D20不等于“logging文档”,则locking单元格F24,否则解锁单元格F24。

当我testing你的代码,它的工作原理,我build议你重构你的代码如下。

 With ThisWorkbook.Sheets("Dashboard") .Unprotect Password:="my password" .Range("F24").Locked = .Range("D20").Value <> "Document Recorded" .Protect Password:="my password", DrawingObjects:=True, Contents:=True, Scenarios:=True End With 

直接使用对象并避免“select”和“ActiveSheet / Workbook / Cell”是最佳实践,如果使用会导致各种不确定的问题。

在运行代码之前,必须closures表格保护。 我假设你使用保护,否则你不会使用单元格lockingfunction。