如何在受保护的VBA创建的工作表上获取未锁定的单元格

时间:2011-03-04 09:56:20

标签: excel-vba vba excel

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

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

2 个答案:

答案 0 :(得分:2)

默认情况下,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

答案 1 :(得分:2)

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

  1. 锁定正在考虑的表格
  2. 查看代码以创建私有子例程(右键单击工作表 - >查看代码 - >选择与此工作表对应的'Microsoft Excel对象')
  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