2011-03-04 381 views
0

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

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

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 
+0

你可以从我的例子,基本上是我在做什么见,但它不工作。我不能右键单击任何单元格,并且vba代码也不起作用。 – 2011-03-04 11:54:03

+0

你说得对。在使用VBA解锁单元格之前,必须取消保护表单。我将用正确的解决方案编辑我的代码 – Kovags 2011-03-04 17:34:15

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 
    
相关问题