首页 文章

即使单元格为空,VBA宏也会运行

提问于
浏览
-1

我是在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

我的问题是,每次我编辑一个单元格(任何单元格)并按工作表中的回车键,它似乎总是会触发第二个if语句 . 见下表的截图:

Initial Table

所以例如在编辑单元格B4之后,按Enter键似乎绕过第一个If语句并直接进入第二个if语句 .

After Editing Cell

我希望在这里实现的是,当列D具有“真实”状态时,我希望宏自动触发,因为列E具有“就绪”状态并且我认为这几乎就是它 .

我在这做错了什么? :(

D列上的公式也只是一个虚拟公式,可根据C列的值模拟自动更新(公式为= if(C4 = 1,“True”,“false”))请参见下面的截图 .

Table Formula

2 回答

  • -2

    在编码之前有些导入的东西,我们需要正确设置 Formulas . 您可以通过“ Show Formulas(Ctrl+`) ”进行检查 . 如果该行不包含正确的公式,然后您操作单元格(例如1/2的列), CellLocation 上的操作将被忽略,我不确定这是否是已知的错误/行为 . 由于操作被忽略,所以“ Second Trigger ”将显示 . 如果我们正确设置了 FormulasCellLocation.Value 将返回True或false .

    根据我的测试,您只需修改if语句( If the Formulas right configured ):

    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
    

    如果公式未正确设置,则 we cannot relay on 代码中的If语句 .

    参考apply Formulas without dragging .

  • 0

    空单元格中似乎没有空字符串 . 有几种方法可以测试单元格中是否有任何内容,即null,nothing,empty,empty-string等.please read here a bit . 基本上

    希望这可以帮助 .

相关问题