[英]VBA - How to lock entire column based on a cell value in this column
很抱歉,这个问题可能看起来像另一个问题,但我是 VBA 的新手,很难获得正确的代码......我想在验证后保护一些数据。 例如,我在 B 列(或任何列)中有数据,我将它们与 manuscrit 原始数据进行比较。 我想在该列中有一个单元格,我说“是”来证明这一点已被检查。 输入“是”后,我希望列中的所有单元格都被锁定。
我找到了锁定整行的代码( 使用 VBA 锁定 Excel 中的行),但无论我尝试什么,我都无法修改它以适用于变量整列(仅锁定特定列,我无法锁定输入“是”的列...)
有人可以帮助我吗? 谢谢 !
您可以稍微调整您正在查看的代码,我认为它会做您想要的。 确保在开始之前将工作表上的所有单元格设置为不受保护。
这设置为检查工作表的第 3 行是否为是。 如果需要,更改第二行的值。
Private Sub Worksheet_Change(ByVal Target As Range)
row_to_check = 3 ' Checking row 3 for "Yes"
If Intersect(Target, Me.Rows(row_to_check)) Is Nothing Then Exit Sub ' exit early if row 3 wasn't changed
Me.Unprotect ' unprotect the sheet
For Each r In Target.EntireColumn.Columns ' cycle through each row that has seen a change
r.Locked = r.Cells(row_to_check, 1).Value = "Yes" ' set it to protected if the second cell on that row is "Yes"
Next
Me.Protect ' reprotect the sheet
End Sub
也许这个解决方案可以帮助:
第 1 步:select 工作表中的所有单元格。 转到属性(单元格格式)-> 安全性并取消激活锁定单元格的复选框(见下图)。
第2步:用密码保护工作表。 在我的示例中,我使用了“billytalent”。
第 3 步:将以下代码复制到工作表的代码区域。 因此打开 Visual Basic 编辑器。 在左侧,您会找到一张包含您的床单的列表。 双击要使用“是”条目锁定单元格的工作表。 将过程复制到代码区域。
Private Const PASSW As String = "billytalent"
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
For Each cell In Target
'only do something, if input is in row 2
If cell.Row = 2 Then
'only do something, if someone write yes in a cell
If cell.Value = "yes" Then
'deaktivate the protection of the sheet
ActiveSheet.Unprotect Password:=PASSW
'lock the cells in the column
ActiveSheet.Columns(cell.Column).Locked = True
'activate the protection
ActiveSheet.Protect Password:=PASSW, userinterfaceonly:=True, AllowFiltering:=True, AllowFormattingCells:=True, AllowFormattingRows:=True, AllowFormattingColumns:=True
ActiveSheet.EnableOutlining = True
End If
End If
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.