重命名工作表时,宏不起作用

时间:2012-10-19 10:57:11

标签: excel vba excel-vba

我在需要保护的工作表上使用宏。这是宏:

wksPartsDataEntry.Unprotect
Sheet11.Unprotect
Application.ScreenUpdating = False

Dim historyWks As Worksheet
Dim inputWks As Worksheet

Dim nextRow As Long
Dim oCol As Long

Dim myCopy As Range
Dim myTest As Range

Dim lRsp As Long

Set inputWks = wksPartsDataEntry
Set historyWks = Sheet11

'check for duplicate order ID in database
If inputWks.Range("CheckID2") = True Then
  lRsp = MsgBox("Clinic ID already in database. Update record?", vbQuestion + vbYesNo, "Duplicate ID")
  If lRsp = vbYes Then
    UpdateLogRecord
  Else
    MsgBox "Please change Clinic ID to a unique number."
  End If

Else

  'cells to copy from Input sheet - some contain formulas
  Set myCopy = inputWks.Range("OrderEntry2")

  With historyWks
      nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
  End With

  With inputWks
      Set myTest = myCopy.Offset(0, 2)

      If Application.Count(myTest) > 0 Then
          MsgBox "Please fill in all the cells!"
          Exit Sub
      End If
  End With

  With historyWks
      With .Cells(nextRow, "A")
          .Value = Now
          .NumberFormat = "mm/dd/yyyy hh:mm:ss"
      End With
      .Cells(nextRow, "B").Value = Application.UserName
      oCol = 3
      myCopy.Copy
      .Cells(nextRow, 3).PasteSpecial Paste:=xlPasteValues, Transpose:=True
      Application.CutCopyMode = False
  End With

  'clear input cells that contain constants
  With inputWks
    On Error Resume Next
       With myCopy.Cells.SpecialCells(xlCellTypeConstants)
            .ClearContents
            Application.GoTo .Cells(1) ', Scroll:=True
       End With
    On Error GoTo 0
  End With
End If

Application.ScreenUpdating = True
wksPartsDataEntry.Protect
Sheet11.Protect
End Sub

宏工作正常。但是,我会将文件分发给其他想要使用密码来保护其工作表的用户。每个用户都想使用不同的密码。 在代码中添加密码不是一个选项,因为该密码是唯一的,我希望其他用户能够在保护时添加自己的密码。 是否存在可以执行以下操作的代码:

Sub Macro1()
wksPartsDataEntry.Unprotect Password: (anything a user might choose as a password)
Sheet11.Unprotect: (anything a user might choose as a password)

所以最后我的宏会根据用户自己选择的密码取消保护和重新保护,而无需用户更改任何代码。

希望我已经足够清楚了,谢谢你的回答!

1 个答案:

答案 0 :(得分:4)

是的 - 你应该在excel-help中查找 unprotect

wksPartsDataEntry.Unprotect(password)是可能的,password是可选参数,因此您可以将其删除。

为了按照您的需要进行操作,请尝试以下操作:

Public Sub MyUnprotect()
  wksPartsDataEntry.Unprotect InputBox( _
                prompt:="Please type your password to unprotect:", _
                Title:="Unprotect")

End Sub

您也可以为 protect 扩展此功能,即将给定密码保存为变量。

如果你想让星星隐藏密码输入,你必须创建自己的UserForm,你可以调用它而不是InputBox。在那里,您可以使用隐藏输入设置输入字段。