2011-03-04 58 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 
    
相關問題