我有两个代码,一个用于保护所有使用输入框中密码的工作表,另一个用于删除 #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
最佳答案
您需要将变量声明为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 .
关于在 Excel 中使用另一个子项的密码的 VBA 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51742796/