Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

if statement with "and" & "or"

Status
Not open for further replies.

netscamp

Technical User
Oct 3, 2003
19
0
0
US
Does VBA allow the following...

Code:
IF x or y and z then
 Dog = true 

end IF

x or y , either one can be true, and z must be true...

I can't find the syntax in HELP. This is used in Excel, but I can't use cell formulas for this task.

Thanks
Robert
 
I hope I understand what you're trying to do....

Try this. Assumes Macro is in cell A1 and possible X, Y, or Z is in A2

Sub XYZ()
'
' XYZ Macro
'
ActiveCell.FormulaR1C1 = _
"=IF(R[1]C[0]=""X"",TRUE,IF(R[1]C[0]=""Y"",TRUE,IF(R[1]C[0]=""Z"",TRUE,FALSE)))"
Range("A2").Select
End Sub
 
Hi!

Yes, but I think a paranthesis might be necessary:

[tt]If (x or y) and z then
dog=true
end if[/tt]

If the issue is to toggle the dog variable, something like this might be used in stead of an if then else consturct:

[tt]dog=(x or y) and z[/tt]

assuming all variables are boolean

HTH Roy-Vidar
 
My basic logic is as follows (and you can try my macro, as it worked):

=if(argument,value if true,value if false). That would be the logic with one argument. Since you have three, you basically nest the same if statement in your value if false, and then do it again for the third. Since you covered all the bases with your true statements, all else if false be default.

All this assumes, of course, that you are simply creating this formula in an excel spreadsheet.
 
Sorry, just noticed you said you can't do it in an excel formula.

I'm just throwing this out as a possibility, but maybe something like this:

Dim A As Object
If A.Value = "X" Then
(Whatever you want to do)
ElseIf A.Value = "Y" Then
(Whatever you want to do)
ElseIf A.Value = "Z" Then
(Whatever you want to do)
Else
(Whatever you want to do if false)
EndIf


 
Just a quick example to show you how I would do it:
Code:
Sub XYZ()
Dim x As Boolean, y As Boolean, z As Boolean
Dim dog As Boolean

' Play around with the T o F settings
x = True 'False
y = False 'True
z = True 'False

' If - Then syntax w/ Or and And Operators
If (x = True Or y = True) And z = True Then
    dog = True
End If

' return dog's value
MsgBox "Dog = " & dog

End Sub

Play around with the commented lines of code setting the X, Y and Z variables around to see what happens.

Good Luck!



Peace! [peace]

Mike

Didn't get the answers that you wanted? Take a look at FAQ219-2884
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top