[英]Range of cells in a row being editable/not editable based on an adjacent cell value
What I require:我需要什么:
Current State in the image attached: Cells A2:E7 are unlocked, all other cells in the sheet remain locked The remainder of the sheet is protected without a password/select unlocked cells only (but could contain a password if required)所附图像中的当前 State:单元格 A2:E7 已解锁,工作表中的所有其他单元格保持锁定 工作表的其余部分在没有密码的情况下受到保护/仅选择未锁定的单元格(但如果需要,可以包含密码)
Code below has to be entered in a Worksheet object, under VBA project properties.下面的代码必须在 VBA 项目属性下的工作表 object 中输入。 I have tested the code and it seems to be working.
我已经测试了代码,它似乎正在工作。 Please report if any problem comes up.
如果出现任何问题,请报告。 If you want to extend the range on which the code works, simply edit currSheet.Range("A2") to currSheet.Range("A100") etc.
如果要扩展代码的工作范围,只需将 currSheet.Range("A2") 编辑为 currSheet.Range("A100") 等。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim currSheet As Worksheet
Set currSheet = ThisWorkbook.ActiveSheet
'declare source range - can be a cell, a range of cells, entire column, entirerow etc.
Dim sourceCell As Range
Set sourceCell = currSheet.Range("A2")
'declare range that will be locked/unlocked
Dim tarRange As Range
Set tarRange = currSheet.Range("B2:E2")
Application.ScreenUpdating = False
currSheet.Unprotect
If Target = sourceCell Then
set_cellLockStatus sourceCell, "Yes", tarRange, True
End If
Application.ScreenUpdating = True
currSheet.Protect
End Sub
Public Sub set_cellLockStatus(source_rng As Range, sourceValueCondition As Variant, target_rng As Range, lockCell As Boolean)
'take source range, check if source condition is met - if yes, lock or unlock target range
source_rng.Locked = False
With source_rng
If source_rng.Value2 = sourceValueCondition Then
target_rng.Locked = lockCell
target_rng.Interior.ColorIndex = 8
Else:
target_rng.Locked = Not lockCell
target_rng.Interior.ColorIndex = 0
End If
End With
End Sub
Another solution.另一种解决方案。 Code in Worksheet - Change event:
工作表中的代码 - 更改事件:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then ' column A changed
ThisRow = Target.Row 'get row number
If Target.Value = "Yes" Then
ThisWorkbook.ActiveSheet.Unprotect 'unprotect sheet
Range("B" & ThisRow).Locked = True
Range("C" & ThisRow).Locked = True
Range("D" & ThisRow).Locked = True
Range("E" & ThisRow).Locked = True
ThisWorkbook.ActiveSheet.Protect 'protect sheeet
Else
ThisWorkbook.ActiveSheet.Unprotect
Range("B" & ThisRow).Locked = False
Range("C" & ThisRow).Locked = False
Range("D" & ThisRow).Locked = False
Range("E" & ThisRow).Locked = False
ThisWorkbook.ActiveSheet.Protect
End If
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.