簡體   English   中英

如何使用vba鎖定excel中單元格中的數據

[英]How to Lock the data in a cell in excel using vba

我想阻止其他人使用VBA編輯我的Excel工作表中的單元格內容。 是否有可能做到這一點?

您可以通過將它們的鎖定狀態設置為False來首先選擇您不希望受保護的單元格(用戶可編輯):

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

然后,您可以保護工作表,並保護所有其他單元格。 執行此操作的代碼仍然允許您的VBA代碼修改單元格:

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

要么

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

嘗試使用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的好方法。

比方說,例如,在一種情況下,如果要鎖定從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"
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

您也可以在工作表的更改事件中捕獲的工作表級別上執行此操作。 如果能滿足您的需求。 允許基於值,標准等動態鎖定...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM