[英]VBA Nested IF statement
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
This is within the Worksheet_Change
sub so shows the message box everytime another cell value changes. 这是在
Worksheet_Change
子目录内,因此每次另一个单元格值更改时都会显示消息框。 I have tried to get around this by adding a boolean variable, set to true when the messagebox has been shown the first time; 我试图通过添加一个布尔变量来解决这个问题,当第一次显示消息框时设置为true;
If Range("P8") = "Y" Then
If messageshown = False Then
messageshown = True
MsgBox "Message here"
Else
End If
Else
End 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. 我有一种感觉,这与我编写嵌套if语句的方式有关,但我已经尝试了各种不同的方式和命令,我放置
else
并end if
但是无济于事。
Use the Target
argument instead - this refers to the actual cell being changed, which is what you are interested in. Test the address of the Target
to see if it's the cell you need and then act accordingly. 请使用
Target
参数 - 这是指您要感兴趣的实际单元格更改。测试Target
地址以查看它是否是您需要的单元格,然后相应地执行操作。 This will stop the message showing when another cell is changed. 这将停止显示另一个单元格更改时的消息。
Private Sub Worksheet_Change(ByVal Target As Range)
With Target
If .Address = "$P$8" And .Value = "Y" Then MsgBox "Message here"
End With
End Sub
Try this code, it first checks which cell is changed, if it is anything but P8, it will not pop the messagebox. 尝试这个代码,它首先检查哪个单元格被更改,如果它不是P8,它将不会弹出消息框。
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
As pointed out by Macro Man, there is a more optimal, more efficient option. 正如Macro Man所指出的,有一个更优化,更有效的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.