excel - 为什么 IsEmpty(Target) 不能在 VBA 中处理我的 Worksheet_Change() 子?
问题描述
我是使用 VBA 的新手,无法理解为什么 IsEmpty(Target) 在我的子例程中不起作用。
我有一个工作表,用户在其中从下拉列表中填写“A”列的值。根据他们选择的值,“B”和“C”列应该发生不同的事情。
1)如果他们从下拉列表中选择“活动”,则“B”和“C”列被解锁,他们可以从另一个下拉列表中为每列选择值。
2)如果他们将值从“Active”更改为其他值,则“B”和“C”列应再次锁定,并且应删除它们各自的值。
3)如果他们删除了“A”列的值,则“B”和“C”列的相应行的值也应该被删除并且单元格应该锁定。这是我遇到问题的地方。
第 1 步和第 2 步工作正常,但是当我删除“A”列的值时,“B”和“C”列没有任何反应。我一直在做很多研究,无法弄清楚我的代码有什么问题,任何帮助将不胜感激。
这是我的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
ActiveSheet.Unprotect
If Target = "Active" Then
Range("B" & ActiveCell.Row & ":" & "C" & ActiveCell.Row).Locked = False
ElseIf Target <> "Active" Then
Range("B" & ActiveCell.Row & ":" & "C" & ActiveCell.Row).ClearContents
Range("B" & ActiveCell.Row & ":" & "C" & ActiveCell.Row).Locked = True
ElseIf IsEmpty(Target) Then
Range("B" & ActiveCell.Row & ":" & "C" & ActiveCell.Row).ClearContents
Range("B" & ActiveCell.Row & ":" & "C" & ActiveCell.Row).Locked = True
End If
ActiveS
我还尝试将 IsEmpty(Target) 更改为 Target = "" 并且没有任何变化,当“A”列中的值被删除时没有任何反应。
解决方案
尝试这个:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, c As Range, notActive As Boolean
Set rng = Application.Intersect(Target, Me.Range("A:A"))
If rng Is Nothing Then Exit Sub
Me.Unprotect
For Each c In rng.Cells 'in case >1 cell is changed
notActive = c.Value <> "Active"
With c.EntireRow.Range("B1:C1") 'range is relative to the row
.Locked = notActive
If notActive Then .ClearContents
End With
Next c
Me.Protect
End Sub
推荐阅读
- android - 导航回屏幕时隐藏的 React Native 状态栏不起作用(Android)
- c# - 用户验证问题
- scala - 用 TimeoutException 或 Awaiting 完成未来?
- selenium - 在 Selenium 中按属性选择
- android - 如何通过 AIDL 在活动和服务之间传递表面视图?
- javascript - 无法通过javascript加载html文件
- java - 日历获取日期并检查两个日期的差异
- assembly - 为汇编寄存器赋值的区别?
- .net - 为什么 Visual Studio 无法加载之前存储的符号?
- asp.net - 将数据表从多列更改为仅 2