[英]multiple if statement conditions vba
I'm very new to VBA so need a little help. 我刚接触VBA,因此需要一些帮助。 I have a macro (BEM) that is dependent on the value of two cells.
我有一个宏(BEM),它取决于两个单元格的值。 I want to be able to run the macro if either of those values is changed.
如果这些值中的任何一个被更改,我都希望能够运行宏。 If either of them is blank, I need the code to do nothing until a value is inputted in both cells.
如果它们中的任何一个为空,我都需要代码什么都不做,直到在两个单元格中都输入了一个值。
Here's what I have so far but it doesn't seem to work: 这是我到目前为止的内容,但似乎不起作用:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$3" Or Target.Address = "$B$4" And (IsEmpty(Range("B3").Value) Or IsEmpty(Range("B4").Value)) Then
Exit Sub
Else
BEM
End If
End Sub
When testing for multiple Ranges, you can use If Not Intersect(Target, Range("B3:B4")) Is Nothing
. 测试多个范围时,可以使用
If Not Intersect(Target, Range("B3:B4")) Is Nothing
。
And instead of checking each Cell if IsEmpty
or Not
, you can use the WorksheetFunction.CountA
for an entire range, in your case your range consists of 2 cells, so you want to check that WorksheetFunction.CountA("YourRange") = 2
. 而不是检查每一个细胞是否
IsEmpty
或Not
,你可以使用WorksheetFunction.CountA
为整个范围,你的情况你的范围由2个细胞,所以要检查WorksheetFunction.CountA("YourRange") = 2
。
Code 码
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B3:B4")) Is Nothing And WorksheetFunction.CountA(Range("B3:B4")) = 2 Then
BEM
End If
End Sub
The and
operator has higher precedence than the or
operator therefore your if
condition in its current format is interpreted as if: and
运算符的优先级高于or
运算符,因此,当前格式的if
条件被解释为:
If Target.Address = "$B$3" Or (Target.Address = "$B$4" And (IsEmpty(Range("B3").Value)) Or IsEmpty(Range("B4").Value)) Then
But you want to goup the or
conditions: 但您想增加
or
条件:
If (Target.Address = "$B$3" Or Target.Address = "$B$4") And ((IsEmpty(Range("B3").Value) Or IsEmpty(Range("B4").Value))) Then
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.