VBA嵌套IF语句 [英] VBA Nested IF statement

查看:494
本文介绍了VBA嵌套IF语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当特定单元格中具有特定值时,我想显示一个消息框.我已经使用以下代码完成了此操作;

I want to show a message box when a specific cell has a particular value in it. I have done this with the following code;

If Range("P8") = "Y" Then
        MsgBox "Message here"
End If

这位于Worksheet_Change子项中,因此每当另一个单元格值更改时,都会显示消息框.我试图通过添加一个布尔变量来解决这个问题,该变量在第一次显示消息框时设置为true;

This is within the Worksheet_Change sub so shows the message box everytime another cell value changes. I have tried to get around this by adding a boolean variable, set to true when the messagebox has been shown the first time;

If Range("P8") = "Y" Then
    If messageshown = False Then
        messageshown = True
        MsgBox "Message here"
    Else
    End If
Else
End If

但是,每次我更改工作表中的单元格时,消息框仍然显示.我觉得这与我编写嵌套的if语句的方式有关,但是尝试了各种不同的方式和顺序来放置elseend if,但无济于事.

However the message box still shows every time I change a cell in the worksheet. I have a feeling it';s to do with the way I have written the nested if statement but have tried various different ways and orders of where I place else and end if but to no avail.

推荐答案

尝试使用此代码,它将首先检查更改了哪个单元格,如果不是P8,则不会弹出消息框.

Try this code, it first checks which cell is changed, if it is anything but P8, it will not pop the messagebox.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$P$8" Then
        If Range("P8") = "Y" Then
            MsgBox "This works"
        End If
    End If
End Sub

正如Macro Man指出的那样,有一个更优化,更有效的选择.

As pointed out by Macro Man, there is a more optimal, more efficient option.

这篇关于VBA嵌套IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆