[英]VBA How to lock the entire sheet except one column and unlock on condition
我正在尝试使用 VBA 锁定工作表以进行修改。
我的目标是锁定除 A 列以外的所有工作表。当一行等于“修改”时,它将解锁整行。
到目前为止,我设法对此进行了编码,但它锁定了我的所有工作表而不是正确的区域。
Private Sub ProtectCells()
LastRow = ActiveSheet.Range("B2").End(xlDown).Row
For i = 1 To LastRow
If Cells(i, 1) = "Modification" Then
Range("B1:F3663").Locked = False
Else
Range("B1:F3663").Locked = True
End If
Next i
ActiveSheet.Protect "pass"
End Sub
Modification
行并解锁它们如下所示:
Option Explicit
Private Sub ProtectCells()
Dim ws As Worksheet
Set ws = ActiveSheet
' lock all cells
ws.Cells.Locked = True
' filter for Modification in column A
With ws.UsedRange
.AutoFilter Field:=1, Criteria1:="Modification"
' unlock all visible rows of the filter
On Error Resume Next ' hide error message if no cells with Modification were found
.SpecialCells(xlCellTypeVisible).EntireRow.Locked = False
On Error Goto 0 ' re-enable error reporting
End With
Selection.AutoFilter 'remove filter
' re-lock row 1 if this is a header row (filter unlocked it)
ws.Rows(1).Locked = True
' unlock column A
ws.Columns("A").Locked = False
' protect
ws.Protect "PASS"
End Sub
请注意,此代码只能运行一次,第二次将出错,因为工作表受到保护。 如果您希望能够多次运行它,您需要在开始时使用ws.Unprotect "PASS"
。
在所需的工作表中使用以下代码。 如果您在 A 列中写入Modification
,此事件将解锁该行,如果您将其删除,则将其锁定。
Option Explicit
Private Const SHEET_PASSWORD As String = "PASS"
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
Me.Unprotect SHEET_PASSWORD
If Me.Cells(Target.Row, "A").Value = "Modification" Then
Me.Rows(Target.Row).Locked = False
Else
'lock row except column A if not modification
Me.Rows(Target.Row).Resize(ColumnSize:=Me.Columns.Count - 1).Offset(ColumnOffset:=1).Locked = True
End If
Me.Protect SHEET_PASSWORD
End Sub
要准备工作表,请先运行以下代码,然后再使用事件锁定除 A 列之外的所有内容。
Public Sub InitialProtection()
Dim ws As Worksheet
Set ws = ActiveSheet
Me.Unprotect SHEET_PASSWORD
ws.Cells.Locked = True
ws.Columns("A").Locked = False
Me.Protect SHEET_PASSWORD
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.