2010-06-14 53 views

回答

3

嘗試使用Worksheet.Protect方法,像這樣:

Sub ProtectActiveSheet() 
    Dim ws As Worksheet 
    Set ws = ActiveSheet 
    ws.Protect DrawingObjects:=True, Contents:=True, _ 
     Scenarios:=True, Password="SamplePassword" 
End Sub 

你應該,但是,關心包括在你的VBA代碼的密碼。如果你只是試圖建立一個簡單的屏障,以防止用戶發生像刪除公式這樣的小​​錯誤,你不一定需要密碼。

另外,如果你想看看如何做某些事情在Excel中的VBA中,嘗試錄製一個宏並查看它生成的代碼。這是開始使用VBA的好方法。

21

你可以先選擇你不想被他們的鎖定狀態設置爲false來保護(是用戶可編輯),該細胞:

Worksheets("Sheet1").Range("B2:C3").Locked = False 

然後,您可以保護工作表,所有其他細胞將受到保護。 的代碼要做到這一點,而且還讓你的VBA代碼修改的細胞是:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True 

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True) 
+1

您可能還想要廣告d密碼,否則只需點擊「取消保護工作表」即可對先前鎖定的單元格進行編輯,這是一件小事。 – Jonathan 2014-02-19 05:53:14

+0

工作表上面的行(「Sheet1」)。Protect(UserInterfaceOnly:= True)應該是Worksheets(「Sheet1」)。保護UserInterfaceOnly:= True,即沒有括號 – dinotom 2016-05-23 19:21:03

+0

@dinotom,看編輯歷史和編輯的人這就解釋了爲什麼 – 2016-05-23 22:40:03

0
Sub LockCells() 

Range("A1:A1").Select 

Selection.Locked = True 

Selection.FormulaHidden = False 

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

End Sub 
0

你也可以做到在工作表的捕獲的工作水平改變事件。如果你的需求更符合你的需求。允許基於價值觀,標準,ECT動態鎖定...

Private Sub Worksheet_Change(ByVal Target As Range) 

    'set your criteria here 
    If Target.Column = 1 Then 

     'must disable events if you change the sheet as it will 
     'continually trigger the change event 
     Application.EnableEvents = False 
     Application.Undo 
     Application.EnableEvents = True 

     MsgBox "You cannot do that!" 
    End If 
End Sub 
2

比方說,例如,在一種情況下,如果從範圍A1要鎖定的細胞然後在下面I50是代碼:

Worksheets("Enter your sheet name").Range("A1:I50").Locked = True 
ActiveSheet.Protect Password:="Enter your Password" 

在另一種情況下,如果你已經有了那麼保護工作表按照以下代碼:

ActiveSheet.Unprotect Password:="Enter your Password" 
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True 
ActiveSheet.Protect Password:="Enter your Password" 
相關問題