【问题标题】:how to have unlocked cells on a protected VBA created worksheet如何在受保护的 VBA 创建的工作表上解锁单元格
【发布时间】:2011-07-08 17:02:42
【问题描述】:

使用 VBA 处理输入数据文件以创建受 Excel(2003) 保护的电子表格(发票)。 然后将电子表格分发到要修改某些指定单元格的其他办公室。 当整个工作表受到保护时,如何创建工作表以允许修改这些单元格? 我尝试过使用下面的代码和其他类似的变体,但它似乎不起作用。 你能帮忙吗?

Private Sub CellLock1()

  Cells.Select
  ' unlock all the cells
  Selection.Locked = False

  ' lock only these cells
  Range("J49:K49").Select
  Selection.Locked = True

 ActiveSheet.Protect DrawingObjects:=True, _
                     Contents:=True, _
                     Scenarios:=True, _
                     UserInterfaceOnly:=True, _
                     AllowFormattingCells:=True, _
                     AllowFormattingColumns:=True, _
                     AllowFormattingRows:=True, _
                     AllowInsertingColumns:=True, _
                     AllowInsertingRows:=True, _
                     AllowInsertingHyperlinks:=True, _
                     AllowDeletingColumns:=True, _
                     AllowDeletingRows:=True, _
                     AllowSorting:=True, _
                     AllowFiltering:=True, _
                     AllowUsingPivotTables:=True

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    默认情况下,excel 上的每个单元格都是锁定的,保护工作簿后,您将无法编辑单元格,除非您事先将它们解锁。

    如果工作表受到保护,即使使用 VBA 代码,您也无法解锁单元格。 因此,如果您想使用代码解锁某些单元格,您必须先取消对工作簿/工作表的保护。

    请试试我的代码:

    Sub UnlockCells()
    
    Sheet1.Unprotect
    Sheet1.Range("A1", "B6").Locked = False 'Unlock the range A1 to B6
    Sheet1.Cells(6, 6).Locked = False 'Unlock the cell F6
    Sheet1.Protect
    
    End Sub
    

    【讨论】:

    • 正如您从我的示例中看到的那样,这基本上就是我正在做的事情,但它不起作用。我无法右键单击任何单元格,并且 vba 代码也不起作用。
    • 你是对的。在使用 VBA 解锁单元格之前,您必须取消保护工作表。我将使用正确的解决方案编辑我的代码
    【解决方案2】:

    这可能有点晚了......但我希望它有所帮助 以下是要做的步骤:

    1. 锁定正在考虑的工作表
    2. 查看代码创建私有子程序(右键Sheet-->查看代码-->选择此Sheet对应的'Microsoft Excel Objects')
    3. 粘贴此代码:

      Private Sub Worksheet_SelectionChange(ByVal Target As Range)
      Dim ws As Worksheet
      Dim inputRange As Range
      
      
      Set ws = Worksheets("WorkSheetName")
      'tell this sub to unprotect only these cells
      Set inputRange = Range("I5,I7,I11")
      
      
      ' If the selected cell is not in the range keep the sheet locked
      If Intersect(Target, inputRange) Is Nothing Then
      'else unprotect the sheet by providing password 
      '(same as the one that was used to protect this sheet)
      Else
      
          ws.Unprotect Password:="password"
          Target.Locked = False
          ws.Protect Password:="password"
      
      End If
      
      End Sub
      

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2019-03-28
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多