![根据表格中另一个单元格的值锁定和解锁单元格](https://linux22.com/image/1539324/%E6%A0%B9%E6%8D%AE%E8%A1%A8%E6%A0%BC%E4%B8%AD%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%8D%95%E5%85%83%E6%A0%BC%E7%9A%84%E5%80%BC%E9%94%81%E5%AE%9A%E5%92%8C%E8%A7%A3%E9%94%81%E5%8D%95%E5%85%83%E6%A0%BC.png)
到目前为止,在互联网上,我已经看到了一些基于另一个单元格值锁定 Excel 工作表中单元格的方法,但是,我还没有找到任何与由于动态表带来的这些单元格包含在表中的情况有关的内容。
下面我有适合我自己的应用程序的 VBA 代码,但它不起作用。
Private Sub Worksheet_Change(ByVal Target As Range) Dim tbl As ListObject
Set tbl = Worksheets("Nursery").ListObjects("TableName")
If Not Intersect(Target, tbl.ListColumns("Bus Discount").Range) Is Nothing Then
Dim CellBusDiscount As Range
Unprotect Password:="Secret"
For Each CellBusDiscount In Intersect(Target, tbl.ListColumns("Bus Discount").Range)
Select Case CellBusDiscount.Value
Case "Yes"
CellBusDiscount.Offset(0, Application.Worksheet.Function.Match("Bus Reason", tbl.HeaderRowRange, 0) - Application.WorksheetFunction.Match("Bus Discount", tbl.HeaderRowRange, 0)).Locked = False
CellBusDiscount.Offset(0, Application.Worksheet.Function.Match("Bus Discount Amt", tbl.HeaderRowRange, 0) - Application.WorksheetFunction.Match("Bus Discount", tbl.HeaderRowRange, 0)).Locked = False
Case "No"
CellBusDiscount.Offset(0, Application.Worksheet.Function.Match("Bus Reason", tbl.HeaderRowRange, 0) - Application.WorksheetFunction.Match("Bus Discount", tbl.HeaderRowRange, 0)).Locked = True
CellBusDiscount.Offset(0, Application.Worksheet.Function.Match("Bus Discount Amt", tbl.HeaderRowRange, 0) - Application.WorksheetFunction.Match("Bus Discount", tbl.HeaderRowRange, 0)).Locked = True
Case Else
CellBusDiscount.Offset(0, Application.Worksheet.Function.Match("Bus Reason", tbl.HeaderRowRange, 0) - Application.WorksheetFunction.Match("Bus Discount", tbl.HeaderRowRange, 0)).Locked = True
CellBusDiscount.Offset(0, Application.Worksheet.Function.Match("Bus Discount Amt", tbl.HeaderRowRange, 0) - Application.WorksheetFunction.Match("Bus Discount", tbl.HeaderRowRange, 0)).Locked = True
End Select
Next cell
Protect Password:="Secret"
End If
End Sub
它不起作用的可能原因;
- 我的 VBA 知识还很业余,因此我还不能有效地运用它
- 代码中使用的相交方法可能不适用于表。
我到底想用上面的代码实现什么目的?
我想确保表格列;"Bus Discount Amount"
并且"Bus Discount Reason"
被锁定不公交车折扣(即如果该列中的值Bus discount
是“是的”然后说明折扣原因(下拉列表)并输入金额或根据“巴士折扣原因”中的选择自动生成金额)
我还使用了工作表函数Match
来确保偏移值是动态的(即,如果我插入新的表列,单元格锁定属性将保持不变)。
答案1
要激活锁定单元格,您必须使用保护表功能:
Private Sub Worksheet_Change(ByVal Target As Range) Dim tbl As ListObject
ActiveSheet.Unprotect
Cells.Locked = false # all cells can be edited (because excel default is Cells.Locked = true)
#here your code where you set cells to Locked = true
...
#end of the code
ActiveSheet.Protect
End Sub