vba - 仅当用户修改现有值时禁用消息框弹出

标签 vba excel

我有 vba 代码,如果输入的值为零,则会弹出 msg 框。如果用户稍后想要将零更改为其他数字,它仍然会弹出 msg 框,然后才允许将零编辑为其他数字。

如果用户更改现有值,我不希望弹出 msgbox

Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False

    If Intersect(Target, Range("b4:af18")) Is Nothing Then

        If Target.Value = 0 Then
            Application.EnableEvents = True
            MsgBox "This is it", vbApplicationModal, "Scikess/Holiday"
        End If 

    End If

    Application.EnableEvents = True

End Sub

最佳答案

我相信您描述的是用户在输入新答案之前点击删除键的情况。在这种情况下,空白单元格的数值为零,并且您在检查用户是否输入了零时会得到误报。

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("b4:af18")) Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Dim trgt As Range
        Application.EnableEvents = False
        For Each trgt In Intersect(Target, Range("b4:af18"))
            If trgt.Value = 0 And trgt.Text = "0" Then
                MsgBox "This is it" & Chr(10) & trgt.Address(0, 0) & " cannot be zero.", _
                    vbApplicationModal, "Scikess/Holiday"
                Application.Undo
                trgt.Activate
                Exit For
            End If
        Next trgt

    End If

bm_Safe_Exit:
    Application.EnableEvents = True

End Sub

我尝试在涉及多个目标时运行代码(例如粘贴或填充操作),但这使得 Application.Undo 难以保留其他有效条目。如果此行为不合适,请发表评论。

也不清楚您希望它在什么范围内使用react。您似乎错过了 Intersect method 中的 Not ,使其对不在该范围内的任何细胞使用react。我已在上面进行了调整以包括您指定的范围,而不是排除它。

关于vba - 仅当用户修改现有值时禁用消息框弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31620979/

相关文章:

excel - 读取 txt 文件、将指定单词放入列中的 VBA 代码

excel - 将行或列添加到选定的 Excel 中

excel - "Run-time error ' 1004 ' Cannot edit a macro on a hidden workbook. Unhide the workbook using the Unhide command"在功能区 XML 中使用 "onLoad"时

excel - 将水平线延伸到图表区域的边缘

macos - 解决 Excel VBA 中的运行时错误

vba - 显示和隐藏事件工作表中的形状

vba - 使用粘贴特殊值

C# Transpose() 方法转置 excel 表中的行和列

excel - 从全局地址簿中获取电话号码