首页 > 解决方案 > 即使单元格为空,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"))请参见下面的屏幕截图。

表格公式

标签: vbaexcel

解决方案


一些在编码之前导入的东西,我们需要正确设置公式。您可以通过“显示公式(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 语句上进行中继。

无需拖动即可应用公式的参考。


推荐阅读