vba - 即使单元格为空,VBA 宏也会运行
问题描述
我对在 Excel 中编码 VBA 很陌生,只需要在 excel 中使用简短脚本的帮助。请参阅下面的脚本:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Dim rng As Range
Set rng = Range("D4:D10")
Dim CellLocation
Set CellLocation = Application.Intersect(Target.Dependents, rng)
If Not CellLocation Is Nothing Then
MsgBox "Current Cell Location is" & CellLocation.Address
If CellLocation.Value = "True" And CellLocation.Value <> "" And CellLocation.Offset(0, 1) = "Ready" Then
'Call Initiate_Email_Sending
MsgBox "Second Trigger"
Else
Exit Sub
End If
End If
End Sub
我的问题是,每次我编辑一个单元格(任何单元格)并在工作表中按 Enter 时,它似乎总是会触发第二个 if 语句。见下表截图:
例如,在编辑单元格 B4 之后,按 Enter 似乎绕过了第一个 If 语句并直接进入第二个 if 语句。
我希望在这里实现的是,我希望宏在 D 列具有“真”状态时自动触发,因为 E 列具有“就绪”状态,我认为就是这样。
我在这里做错了什么?:(
D 列上的公式也只是一个虚拟公式,用于根据 C 列的值模拟自动更新(公式为 =if(C4=1,"True","false"))请参见下面的屏幕截图。
解决方案
一些在编码之前导入的东西,我们需要正确设置公式。您可以通过“显示公式(Ctrl+`) ”来检查它。如果该行不包含正确的公式,然后您操作一个单元格(例如具有 1/2 的列),则对CellLocation的操作将被忽略,我不确定这是否是已知的错误/行为。由于操作被忽略,所以会显示“<strong>Second Trigger”。如果我们正确设置了公式,CellLocation.Value将返回 True 或 false。
根据我的测试,您只需修改您的 if 语句(如果公式正确配置):
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Dim rng As Range
Set rng = Range("D4:D100")
Dim CellLocation
Set CellLocation = Application.Intersect(Target.Dependents, rng)
If Not CellLocation Is Nothing Then
MsgBox "Previous Cell Location is " & CellLocation.Address
'MsgBox "Previous Cell Offset's value is " & CellLocation.Offset(0, 1).Text & CellLocation.Offset(0, 1).Value
If IsEmpty(Target) Or IsEmpty(Target.Offset(0, -1)) Then Exit Sub
If CellLocation.Value = "True" And CellLocation.Offset(0, 1).Value = "Ready" Then
'Call Initiate_Email_Sending
MsgBox "Second Trigger"
Else
Exit Sub
End If
End If
End Sub
如果公式设置不正确,我们将无法在代码中的 If 语句上进行中继。
无需拖动即可应用公式的参考。
推荐阅读
- c# - 为什么“缩放”的显示设置和使用超过 1 个显示器会导致我的 WPF 应用程序窗口在我的显示器上的不同区域进行动画处理?
- elasticsearch - Elasticsearch must_not 在嵌套查询中
- r - xts 对象中的重复日期导致错误的索引
- android - RecyclerView 滚动期间的 java.lang.OutOfMemoryError
- javascript - React Material-UI - 样式标签
- android - 正确使用 WindowManager.removeViewImmediate()
- python - 在特定目录中创建 Python 虚拟环境
- php - 在 GCM 事件中解析时间戳时出错
- azure - 按名称解析 pod 的 IP
- javascript - 使用 Javascript 的向导