【发布时间】:2016-05-12 22:59:50
【问题描述】:
根据特定单元格的值,我可能需要取消保护工作表,设置范围以锁定并重新保护工作表。相反,如果单元格的值(在这种情况下,单元格 B4 等于“工作”),那么我需要取消保护工作表,解锁单元格,然后重新保护工作表。这样做的原因是,当单元格 B4 不等于工作时,我想停止用户切换到单元格 A8:B19。当 B4 = "work" 时,用户可以在单元格 A8:B19 中输入数字。 B4 “工作”时输入的选项有限,我设置了仅选中未锁定单元格之间的选项卡,这使得输入更容易。
目前我有这个:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B4")) Is Nothing Then
If Range("B4").Value = "work" Then
Shapes("Rectangle 1").Visible = False
Application.EnableEvents = False
ActiveSheet.Unprotect
ActiveSheet.Range("A8:B19").Locked = True
ActiveSheet.Protect ‘When the code hits this line it throws error 400
Application.EnableEvents = True
End If
If Range("B4").Value <> "work" Then
Shapes("Rectangle 1").Visible = True
Application.EnableEvents = False
ActiveSheet.Unprotect
ActiveSheet.Range("A8:B19").Locked = True
ActiveSheet.Protect ‘When the code hits this line it throws error 400
Application.EnableEvents = True
End If
End If
End Sub
很明显,“ActiveSheet.Protect”导致错误发生取决于单元格 B4 的值,但它总是如此。注释掉有问题的行允许 VBA 代码按预期运行,但它会使工作表保持解锁状态。我已经尝试将“ActiveSheet.Protect”行移动到子的下方,在不同的子等中调用它并且没有运气,它总是会导致错误 400。我知道 Elseif 无疑会是更好的做法,但是我改变了从 If, ElseIf End If 看是否有什么不同。没有。
奇怪的是,我在另一个 Excel 表格中尝试了类似的事情来证明这个原理,代码如下:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1")) Is Nothing Then
Dim i As Integer
If Cells(1, 1) = "unlock" Then
i = 1
Shapes("Oval 1").Visible = False
Application.EnableEvents = False
ActiveSheet.Unprotect
For i = 1 To 5
Cells(i, 2) = i
Next i
ActiveSheet.Range("C1:C5").Locked = False
ActiveSheet.Protect
ElseIf Cells(1, 1) <> "unlock" Then
i = 1
Shapes("Oval 1").Visible = True
Application.EnableEvents = False
ActiveSheet.Unprotect
For i = 1 To 5
Cells(i, 2) = ""
Cells(i, 3) = ""
Next i
ActiveSheet.Range("C1:C5").Locked = True
ActiveSheet.Protect
End If
Application.EnableEvents = True
End If
End Sub
这完全符合我的预期,并且做类似的事情。除了不同的单元格和一个 for 循环之外,我看不出上面的两个代码示例在 unprotect、更改锁定变量、保护过程方面有任何区别。
很困惑,非常感谢任何帮助。
【问题讨论】: