excel - VBA在工作表的给定范围内保护和取消保护

标签 excel vba

我已应用此宏来保护和取消保护工作表中给定范围的单元格这是我在此宏中面临的问题
当我运行这个宏时,这个宏在给定的单元格 A1 到 D20 范围内受到保护,当我再次运行这个宏以在给定范围内取消保护时,它不是取消保护

Sub lockcells()
 Dim Rng
 Dim MyCell
 Set Rng = Range("A1:D20")
 For Each MyCell In Rng
 If MyCell.Value = "" Then
 Else: ActiveSheet.UnProtect Password:="123"
 MyCell.Locked = True
 MyCell.FormulaHidden = False
 ActiveSheet.Protect Password:="123", UserInterFaceOnly:=True
 End If
 Next
End Sub

我想用单个宏保护和取消保护

最佳答案

一些小的调整使其“保护/取消保护”。
我假设您只想保护/锁定一个单元格,如果它是 不是 空的。

Option Explicit

Sub lockcells()
Dim Rng As Range
Dim MyCell As Object

Set Rng = Range("A1:D20") 'Set range to lock cells

If ActiveSheet.ProtectContents = True Then 'Check if sheet is protected
    ActiveSheet.Unprotect Password:="123" 'Password to unprotect
Else
For Each MyCell In Rng
    If MyCell.Value <> "" Then 'If cell is empty, if not empty lock the cell
        MyCell.Locked = True 'Lock cell
        MyCell.FormulaHidden = False 'Don't hide formulas
    End If
Next MyCell
ActiveSheet.Protect Password:="123", UserInterFaceOnly:=True 'Protect Sheet
End If
End Sub

如果您希望除范围之外的所有单元格都是可编辑的,您可以添加以下代码:
'Else
    ActiveSheet.Cells.Locked = False
    ActiveSheet.Cells.FormulaHidden = False
    'For Each MyCell In Rng
这只会使 Range("A1:D20")受密码保护。所有其他单元格都可以自由编辑。

关于excel - VBA在工作表的给定范围内保护和取消保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69325580/

相关文章:

excel - 版本控制 - 运行时错误 80070006 句柄无效

php - 通过 PHP 操作 Excel 文件

python pandas 公式到数据框

使用格式(日期)函数保存文件时出现VBA错误

performance - 运行缓慢的公式宏

excel - 如何覆盖动态编写的控件的 control_Change 事件?

excel - 在用户窗体中使用类模块变量(需要错误 '424' 对象)

python - 用户文件夹 VBA 引用位置(对于 xlwings)

c++ - CSV 格式不正确

vba - 带有 vba 的数据透视表