我有两个代码,一个用于保护所有使用输入框中的密码的工作表,另一个用于删除#REF!
错误。在第二个代码上,我需要先取消保护工作表才能删除行。现在,我试图找出如何从第一个代码中使用密码来取消保护工作表,以便第二个代码可以删除#REF!
错误行?
不确定是否可能,但也许以前有人遇到过相同的问题。
感谢您的帮助。
Sub ProtectAllSheets()
Dim pwd1 As String, pwd2 As String
pwd1 = InputBox("Enter your password", "")
If pwd1 = "" Then Exit Sub
pwd2 = InputBox("Enter the password again", "")
If pwd2 = "" Then Exit Sub
'Checks if both the passwords are identical
If InStr(1, pwd2, pwd1, 0) = 0 Or _
InStr(1, pwd1, pwd2, 0) = 0 Then
MsgBox "Please type the same password. ", vbInformation, ""
Exit Sub
End If
For Each ws In ActiveWorkbook.Sheets
If ws.ProtectContents = False = True Then
ws.Protect Contents:=True, Scenarios:= _
True, AllowFormattingCells:=True, AllowDeletingRows:=True, Password:=pwd1
End If
Next ws
MsgBox "Sheets are protected."
End Sub
Sub DeleteRows() ' Cells which contain an Error Formula
ActiveSheet.Unprotect pwd1
Dim c As Long
For c = 400 To 2 Step -1
If IsError(Cells(c, 3)) Then
Rows(c).EntireRow.Delete
End If
Next c
ws.Protect Contents:=True, Scenarios:= _
True, AllowFormattingCells:=True, AllowDeletingRows:=True, Password:=pwd1
End Sub
答案 0 :(得分:2)
您需要将变量声明为Public
。
Public pwd1 As String
Sub ProtectAllSheets()
'NO dim for pwd1 here
pwd1 = InputBox("Enter your password", "")
'your code here
End Sub
因此在您的所有过程和功能中都可用。
但是我建议使用.Protect UserInterFaceOnly:=True
这样可以保护工作表免受用户编辑,但可以让VBA不受限制地对其进行编辑。
因此,您只需要在Workbook_Open()
事件中保护工作表,如下所示:
Private Sub Workbook_Open()
Sheets("Sheet1").Protect Password:="Secret", UserInterFaceOnly:=True
Sheets("Sheet2").Protect Password:="Secret", UserInterFaceOnly:=True
'Repeat with the name and password of additional sheets to be manipulated by VBA.
End Sub
这样,您无需为每个VBA动作都提供保护/取消保护。
有关完整的操作方法和更多信息,请参见:Speedup Excel VBA Macros with Protect UserInterFaceOnly。