【问题标题】:Protect A Specific Sheet Button?保护特定的工作表按钮?
【发布时间】:2017-05-29 12:52:44
【问题描述】:

您好,我有一个按钮,可以让我的老板根据他输入的工作表名称来删除工作簿中众多工作表中的其中一个工作表。此删除工作表按钮受密码保护,因为其他人使用工作簿我不希望他们删除任何内容。

现在这不会阻止他们右键单击特定工作表并删除,因此我需要一种方法来在未按下“删除工作表”按钮时保护所有工作表,并在正确输入该按钮的密码后取消保护所有工作表, 因为按钮无法移除受保护的工作表

删除工作表按钮代码:

    Private Sub CommandButton4_Click()

Dim delSheet As String
Dim response As String
Dim SheetFound As Boolean
Dim MyPass As String
Dim MyPasswrd As String, answ As String

 MyPasswrd = "test"                                                             'password verification puts trigger in cell A100, an deletes when file close
 If Range("A101").Value <> "OK" Then
     answ = InputBox("Please Enter The Password To Continue.", "Enter Password")
        If answ <> MyPasswrd Then
             MsgBox "Incorrect Password!", vbExclamation, "Warning"
            Exit Sub
        End If
    Range("A101").Value = "OK"
End If

delSheet = InputBox("Please Enter The LAST NAME Of The DTS You Want To Remove", "Remove A DTS")                     'user input

If delSheet = "" Then
MsgBox "You Did Not Complete The Entry.", vbOKOnly + vbInformation, "Warning"                       'if NULL input displays this message
Exit Sub

Else
  If IsLetter(delSheet) = False Then GoTo Display                                                   'checks the user input

response = MsgBox("WARNING!! This Action Cannot Be Undone, Do You Still Want To Continue?", vbExclamation + vbYesNo, "Warning")     'verfies user input


If response = vbYes Then                                                                'if input is yes  selects sheet IF ITS FOUND
On Error Resume Next

        ActiveWorkbook.Sheets(delSheet).Select
        If Err = 0 Then SheetFound = True                                               'searches for sheet

    On Error GoTo 0

    If SheetFound = False Then                                                      'if sheet not found displays this message

        MsgBox prompt:="The sheet '" & delSheet & "' Could Not Be Found In This File!", Buttons:=vbExclamation, Title:="Search Result"
        Exit Sub

    Else

 Application.DisplayAlerts = False                                                  'Finally deletes sheet and bypass xcel warning for sheet deletion
 Sheets(delSheet).Delete
 Application.DisplayAlerts = True

MsgBox ("The DTS " & delSheet & " Was Successfully Removed")                                    'message for sucessfully deleting the sheet
Application.Goto Reference:=Worksheets("Control Center").Range("B1"), Scroll:=True
End If

Else

response = vbNo                                                                         'if user does not want to delete sheet exits window
Exit Sub

Display:
     MsgBox "Invalid Character In Last Name. Please Only Use Letters And Numbers(1-9), NOT Spaces and Specail Characters (! @ # $ % ^ & * - + = \ _ .)", vbExclamation, "Warning"

End If
End If
End Sub

【问题讨论】:

  • 表格删除不能停止,至少在没有大量代码/结构保护的情况下不能。但是在保存工作簿之前,您始终可以确定工作表是否存在,如果它不存在,那么您可以阻止保存工作簿。这是最简单最简单的路线。
  • 我做了一些研究,发现了这个Delete A protected sheet,但我不知道如何在我的代码中实现它。基本上,您创建一个包含所有工作表名称的控制工作表,然后当您单击控件中的工作表时,它会运行一个宏来取消保护所有工作表以便将其删除,然后工作簿中的工作表将恢复为受保护状态。

标签: vba excel


【解决方案1】:

如果您有 Excel-2013 或 Excel-2016 那么,您可以使用Workbook_SheetBeforeDelete 事件。 在工作簿模块中添加以下代码:

Option Explicit

Public IsPasswordOK  As Boolean
Public IsDeleteOK    As Boolean

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Not IsDeleteOK Then
        MsgBox "You deleted a sheet without permission. Can't save the file."
        Cancel = True
    End If
End Sub

Private Sub Workbook_Open()
    IsDeleteOK = True
End Sub

Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
    If IsDeleteOK Then
        IsDeleteOK = IsPasswordOK
    End If
End Sub

CommandButton4_Click() 代码行 Sheets(delSheet).Delete 之后添加此行

ThisWorkbook.IsPasswordOK=True

对于 Excel-2013

之前的版本

首先添加一个模块名称mdlSheetWatch。在该模块中添加以下代码。

Option Explicit

Public IsPasswordOK  As Boolean
Public dctSheets
Public Function IsSheetsOk()

    Dim wks As Worksheet
    Dim lCtr    As Long
    Dim bResult As Boolean

    If IsPasswordOK Then
        bResult = True
        Exit Function
    Else

       bResult = True
        For Each wks In ThisWorkbook.Worksheets
           If Not dctSheets.exists(wks.CodeName) Then
            bResult = False
            Exit For
           End If
        Next

    End If

    IsSheetsOk = bResult

End Function

Public Function LoadSheetList() As Object
     Dim wks As Worksheet
     Dim dctTemp As Object

     Set dctTemp = CreateObject("Scripting.Dictionary")

      For Each wks In ThisWorkbook.Worksheets
        dctTemp.Add wks.CodeName, wks.Name
      Next

    Set LoadSheetList = dctTemp

End Function

现在在工作簿模块中,添加以下代码

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Not mdlSheetWatch.IsSheetsOk Then
        MsgBox "You deleted/renamed a sheet without permission. Can't save the file."
        Cancel = True
    End If
End Sub

Private Sub Workbook_Open()
   Set dctSheets = mdlSheetWatch.LoadSheetList
End Sub

最后,在CommandButton4_Click() 代码行之后 Sheets(delSheet).Delete 添加这一行

mdlSheetWatch.IsPasswordOK=True


这应该防止没有密码的用户在删除/重命名/添加工作表后保存工作簿。

【讨论】:

  • 当您说用户没有密码时,您的意思是为了打开工作簿,他们需要密码吗?
  • 不,我的意思是有人没有你的密码“测试”来删除工作表。它将如何工作。第一个商店的床单清单。其次,当您的代码删除工作表时,存储一个标志以跳过任何检查。第三,当文件被保存时,如果当前工作表列表与实际工作表匹配,它将检查(如果标志为真,则跳过此)。如果是允许保存。如果否,则不允许保存。
  • 在“SheetBeforeDelete”中,我还会通知用户,由于 bla bla,工作簿将不会被保存,以免它徒劳地工作(也许几个小时!)
  • 为什么投反对票?代码有问题吗?请指出。
  • 我使用了 2013 的 excel 代码,但由于某种原因,如果我复制已经存在的工作表来制作新工作表。然后重命名该复制的工作表,然后我尝试使用“删除工作表”按钮将其删除,但它会删除,但我无法保存我的工作簿,因为它认为我未经许可将其删除???
【解决方案2】:

Worksheet 类的事件BeforeDelete 没有Cancel 选项,但这是执行取消操作的解决方法。

1- 在一个普通的模块中,放入这个例程:

Sub unprotectThis()
    ThisWorkbook.unprotect
End Sub

2- 在要防止删除的工作表的代码模块中,添加此事件处理程序:

Private Sub Worksheet_BeforeDelete()
    ThisWorkbook.Protect
    MsgBox "This sheet can be deleted only by the administrator through the dedicated button", vbExclamation
    Application.OnTime Now + TimeSerial(0, 0, 1), "unprotectThis"
End Sub

我们以某种方式“模拟”了取消选项。一秒钟后,工作簿将再次不受保护。

3- 最后,在按钮的处理程序中,您要求输入密码,在实际执行删除之前禁用事件。这不会调用上面的 Worksheet_BeforeDelete 处理程序。在离开之前恢复事件:

Private Sub CommandButton4_Click()
    On Error goto RestoreEvents
    Application.EnableEvents = false
    ...
    ' your routine that checks for password and performs the delete...
    ...
RestoreEvents:
    Application.EnableEvents = true
End Sub

请注意,此解决方案甚至不需要保护工作簿,它只保护给定的工作表。

【讨论】:

  • 因此,如果用户没有按下“删除工作表”按钮,它会保护 1 张工作表/在给定时间试图删除的任何工作表?不错。
  • @Deathkamp 没错。您可以将此保护技术应用于任何单个工作表,而无需保护工作簿:)
猜你喜欢
  • 2018-03-11
  • 2018-04-18
  • 1970-01-01
  • 2021-05-07
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2018-01-12
相关资源
最近更新 更多