我花了几个小时尝试不同的修改,其中一定不起作用。 VBA调试器不会抛出任何错误,当我测试脚本时,它似乎永远不会运行。
每当我从任何工作表标签中保存文档时,如何修改以下脚本以针对特定工作表运行?
谢谢
下面的脚本将锁定包含值的单元格,然后在保存之前用密码保护工作表。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
On Error Resume Next
Dim Cell As Range
With ActiveSheet
.Unprotect Password:=""
.Cells.Locked = False
For Each Cell In Application.ActiveSheet.UsedRange
If Cell.Value = "" Then
Cell.Locked = False
Else
Cell.Locked = True
End If
Next Cell
.Protect Password:=""
'Protect with blank password, you can change it
End With
Exit Sub
End Sub
答案 0 :(得分:1)
更改ActiveSheet
并使用For Each
循环,如下所示:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
On Error Resume Next
Dim Cell As Range
For Each sh In Array("Sheet1", "AnotherSheet", "OtherSheet")
With Sheets(sh)
.Unprotect Password:=""
.Cells.Locked = False
For Each Cell In Application.ActiveSheet.UsedRange
If Cell.Value = "" Then
Cell.Locked = False
Else
Cell.Locked = True
End If
Next
.Protect Password:=""
End With
Next
End Sub
答案 1 :(得分:0)
这应该会对您有所帮助(当您遇到此事件以及它何时开始时,您会收到消息让您知道:
WHERE name = ...
答案 2 :(得分:0)
可以显着缩短代码(运行时间)
SpecialCells
而不是循环遍历每个单元格更新
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
For Each sh In Array("Sheet1", "AnotherSheet", "OtherSheet")
With Sheets(sh)
.Unprotect
.Cells.Locked = True
On Error Resume Next
.Cells.SpecialCells(xlBlanks).Locked = False
On Error GoTo 0
.Protect
End With
Next
End Sub