Understanding the if conditional statement

Level:
Level1

A conditional statement is a way for you to execute commands based on if a condition is true. It is easiest to understand by examples. This tutorial relies on you understanding how variables work. If you don't understand variables I suggest you check out this tutorial first: Using variables in Visual Basic (VB6) Tutorial.

Here is an example of the most common conditional statement used - the if statement.
Private Sub Command1_Click()
   Dim var1 As Integer   
   var1 = 10
      
   If var1 = 10 Then
      MsgBox "The condition is true."
   End If
End Sub

In line 2 we declare a variable called var1 as an integer. Then in line 3 we assign the value 10 to it. Now the interesting part happens in line 5. We are comparing var1 to the value 10. If they are equal then the commands between the Then statement and the End If statement are executed. In our case this is line 6 (The MsgBox statment). If you press F5 to run this program and click the button you will see a message box appear that says "The condition is true."

Now if you change line 3 to: var1 = 5 and run the program again no message box will appear. That is because the condition var1 = 10 is false. This is like asking does 5 = 10. Obviously this is not true so our code inside the if statement is not executed. We can do other comparisons besides just he = statement.

Here is a list of all the VB6 comparison operators

 <  Less Than
 <=  Less Than or Equal to
 >  Greater Than
 >=  Greater Than or Equal to
 =  Equal to
 <>  Not Equal to

Try some of these out in our program and see how they work. Its pretty self explanatory. Just read the statement to yourself with the words described above and it will make sense. For example if we set var1 = 5 and have the statement If var1 < 10 Then ... We can read it as follows if 5 is Less Than 10 - This would be true so our code gets executed.

There are times when you want code to not only be executed if our conditional statement is true, but you want other code to be executed if your statement is false. You can do this with the else clause. Like this code does.

Private Sub Command1_Click()
   Dim var1 As Integer
   
   var1 = 5
   
   If var1 = 10 Then
      MsgBox "The variable is ten"
   Else
      MsgBox "The variable is not ten"
   End If
End Sub 

Line 6 of this code compares the value of var1 to 10. If they are equal then the code between the if ... then statement and the else statement is executed. In our case that would be Line 7 - and a message box would appear saying The variable is ten. If the comparison var1 = 10 is false then the else portion of our code will be executed and a message box will appear saying The variable is not ten. If you press F5 and run this program you will see that since the comparison of 5 = 10 is false a message box will pop up saying The variable is not ten.

Try playing around with this some. Add more lines of code between your if and else clauses. Everything should work they way you would expect it to. If you have any questions please leave a comment below or in the forum.


    

If you enjoyed this post, subscribe for updates (it's free)

trying to write a code for macros in Excel

Hello,

I have some data where i have dates in a coloumn.
I want those dates to be changed into the respective quarter.
i tried to write the code using if > and < then change the coloumn to Q3
i couldnt succeed writing such kind of code.
kindly someone help me with writing this logic.

Quarters

Try the following code:

Sub DtQuarter()
    Dim I As Long, R As Long
    R = Cells(Rows.Count, 1).End(xlUp).Row
 
    For I = 1 To R
        Select Case Month(Cells(I, 1).Value)
            Case 1 To 3:
                Cells(I, 2).Value = "Q1 of " & Year(Cells(I, 1).Value)
            Case 4 To 6:
                Cells(I, 2).Value = "Q2 of " & Year(Cells(I, 1).Value)
            Case 7 To 9:
                Cells(I, 2).Value = "Q3 of " & Year(Cells(I, 1).Value)
            Case 10 To 12:
                Cells(I, 2).Value = "Q4 of " & Year(Cells(I, 1).Value)
        End Select
    Next
End Sub

Your dates should be on A column and the code will fill the B column with the pattern "[Q1, Q2, Q3, Q4] of " the A's year.

programming

i have a problem with using conditional statements for selection and repetition and how to create an interface in vb6.0 can u pliz help

Need help with if statement in vba

Hi

I need to create a macro to show the following:

If (I3<>0,I3*G3,H3*G3) and this repeats itself for cell N3,R3, V3,Z3 ETC.

After that I need to add all this to give a the big total.

I tried looking at the code in VBA and see below.

Is this how it should be?
Thank you for helping.

Private Sub CommandButton1_Click()

' nonbillable_actual_spend Macro
'

'
Range("J3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("N3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("R3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("V3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("Z3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("AD3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("AH3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("AL3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("AP3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("AT3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("AX3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("BB3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("BF3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
Range("BJ3").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
End
End Sub

Basic if statment.

Hello, I have only been trying to program for 3 days now, I am picking it up reasonably well (I think) but I am having a problem with an if statement. The problem is the program actually runs fine, it gives the answer "Congratulations" when a number between 10 and 20 is presented and "Sorry try again" when any other number is entered. The problem arises when nothing is entered, the program freezes and I am unsure how to get around this and I would really appreciate some help, this is the code I am using:

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim number As Integer
Dim answer As String

number = TextBox1.Text

If number >= 10 And number <= 20 Then
answer = "Congratulations"

Else
answer = "Sorry try again"

End If

MsgBox(answer)

End Sub
End Class

Thank you for reading

If Then Statement

Hi,

I want to know how to put "If Then" statement in the following
1. There are 2 combo boxes.
2. First combo box has three names ie. John, David, Bret
3. Second combo box has nine articles.
4. If John selected from 1st combo box then the 2nd combo box display 1-3 articles, If David selected then the 2nd combo box display 3-6 articles and Bret selected from 1st combo box then the 2nd combo box display last 3 (7-9) articles.

Thank you

Computer PRogramming (VisuaL basic 6.0)

can yOu give me some help about scientific Calculator codes ..

Plz Email mEh @ robles_mjane@yahoo.com

Fibonacci

Hi, do you know the codes for Fibonacci?

please need help I'm trying

please need help
I'm trying to do the comparison of numbers if it is integer or not, for example:

if x <> integer then msgbox("not integer")
else msgbox("integer")

but in the fact i don't know how to do that, I mean the right code for doing that.

Validate input if integer.

Good day,

Please see the codes below for your reference.

'=====================================================================
Option Explicit

Private Sub cmdCompare_Click()

With Me

If isInteger(.txtInput.Text) Then
MsgBox "Integer.", vbInformation
Else
MsgBox "Not integer.", vbCritical
End If

End With

End Sub

Private Function isInteger(ByVal value As String)

If IsNumeric(value) Then
isInteger = True
Else
isInteger = False
End If

End Function
'=======================================================================

You'll be needing one TextBox named txtInput and one CommandButton named cmdCompare then that's it you're good to go just copy the codes above.

I hope this can help.

Best regards,

Tobee

about my program

can you help me to do my project plzzz...
we need to make a program by using conditional statement of visual basic 6.0

Help...

My e-mail is: chrzgt7@hotmail.com

Send me there what you need and I can help you with your program.

ChrisGT7

are you sure going to help

are you sure going to help this idiot?

greater than and less than

PLEASE HELP!

i'm noob here at VB 6.0, and i'm having a problem because of my project.. i dont know how to use the
>=<....... my project is like this..... if then else statement...
-----------------------------------------|
10,000 above = 12% deduction |
8,000-9,999 = 10% deduction | <----LEGEND for TAX!!! the DEDUCTIONS
5,000-7,999 = 5% deduction |
-----------------------------------------|
and after that it comes like a payroll system...

my codes are these..

dim a, b, c, d, e as integer

Private Sub grosspay_Click()
a = Val(Text1.Text)
b = Val(Text2.Text)
c = a * b
Label1.Caption = c

Private Sub tax_Click()
If Label2.Caption >= "10000" Then
Label3.Caption = (c * 0.12)

elseif Label2.Caption <= "9999" Or Label2.Caption >= "8000" Then
Label3.Caption = (c*.10)<----follow up question here... is .1 and .10 are the same? coz when i put .10 it come .1????
End If

sorry for my english pls help!!

or email me nickson_acuna@y.c

Please learn proper english

Please learn proper english before you post to here

.1 or .10

Yes, according to mathematics the 0.1 and 0.10 are the same numbers.

That's why the VB changes the .10 to .1.

Simple voting code

Hey guys you're all doing a splendid job here. i'm a bit new to programming and i'm having trouble with this little project of mine.
i'm trying to make a simple voting programe that if a voter ticks one of the radio boxes of a candidate and clicks ok then a counter of one is added to the candidate,
then returns back to the voting platform.
i'll really appreciate any help, its really urgent

need software

pls i urgently need vb6.0 enterprise edition software some help me out

IF statement

I'm new to VB... i'm trying to write a program that will display money made by a movie theater, the information I have is as follows;
input: TypeOfNight
IF TypeOfNight = "R" or
TypeOfNihgt = "r" TRUE Input: Ticket , Input:Popcorn, Input:Floats, Total = Tickets *5 + Popcorn *2 + Floats * 3, Output:Total
IF TypeOfNight = "C" or
TypeOfNight = "c" TRUE Input: Ticket , Input:Popcorn, Input:Floats, Total = Tickets *7 + Popcorn *1.25 + Floats * 1.5, Output:Total
False : output: invalid type of night - please try again..

No Idea as how to start with this simple program, will you help?

Done!

Here is the code you are looking for:

Dim TypeN As String
Dim Tickets As Long, PopCorn As Long, Floats As Long

Private Sub Form_Activate()

While Not TypeN Like "[rRcC]"
TypeN = InputBox("Please enter Type-Of-Night:", "Type of Night")
If Not TypeN Like "[rRcC]" Then MsgBox "Invalid type of night - Please try again ...", , "INVALID DATA"
Wend

Tickets = InputBox("Please enter Tickets money:", "TICKETS")
PopCorn = InputBox("Please enter PopCorn money:", "POP-CORN")
Floats = InputBox("Please enter Floats money:", "FLOATS")

If TypeN Like "[rR]" Then
Print Format(Tickets * 5 + PopCorn * 2 + Floats * 3, "#,###0.00")
Else
Print Format(Tickets * 7 + PopCorn * 1.25 + Floats * 1.5, "#,###0.00")
End If

End Sub

Home made web viewer program

hi everybody, i'd like to know if it's possible to create a program that has 2 vertical columns. in one window you see html code, in the other window you see your output rendered from the web browser of your choice.
i'm not trying to copy them but, here's where i got the idea from:
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro
i realize they probably use some server side scripting. i'm not into that yet. so, that's not an option. notepad++ which is free, almost
does what i want, but the resulting page open in a new window. anybody with some suggestions would be greatly appreciated.
thanks!

I draw a text box. And I

I draw a text box. And I want the user can only input the number. And when the user type the letter in it, it appear nothing. Could u tell me how to do it? Thank you in advance!

Only Digits

You should use the event KeyPress of the textbox. Here is the code:

Private Sub Text1_KeyPress(KeyAscii As Integer)
If (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 8 Then KeyAscii = 0
End Sub

The keyascii of each digit (0 - 9) is {48 - 57}.
So, if the user presses any button that its keyascii doesn't belong in this field {48 - 57} the program must print nothing (keyascii = 0).
I used the keyascii 8 because if the user types a wrong digit, he should be able to correct it with the Backspace.

An alternative code is the following one:

Private Sub Text1_KeyPress(KeyAscii As Integer)
If (Chr$(KeyAscii) < "0" Or Chr$(KeyAscii) > "9") And KeyAscii <> 8 Then KeyAscii = 0
End Sub

Choose any you like. I hope I helped you!

Help!

This is one of the first programs i have tried to create. In this program you ype certain foods into a text box and click the button and its country of orgin appears.
Private Sub Btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn1.Click
If txt1.Text = "Taco" Then lbl1.Text = "Mexico!"
If txt1.Text = "Perogie" Then lbl1.Text = "Poland!"
If txt1.Text = "Spaghetti" Then lbl1.Text = "Italy!"
If txt1.Text = "Hamburger" Then lbl1.Text = "United States of America!"
If txt1.Text = "Maple Syrup" Then lbl1.Text = "Canada!!"
If txt1.Text = "taco" Then lbl1.Text = "Mexico!"
If txt1.Text = "perogie" Then lbl1.Text = "Poland!"
If txt1.Text = "spaghetti" Then lbl1.Text = "Italy!"
If txt1.Text = "hamburger" Then lbl1.Text = "United States of America!"
If txt1.Text = "maple Syrup" Then lbl1.Text = "Canada!!"
My question is: is there a way to make it so if the user types anything other than what i have listed, the program will display a message?

"Select Case" instead of "If... then"

I believe the best solution to your problem is the "Select Case" statement. Here is what I suggest:

Select case txt1.Text
Case "Taco", "taco": lbl1.Caption = "Mexico!"
Case "Perogie", "perogie": lbl1.Caption = "Poland!"
Case "Spaghetti", "spaghetti": lbl1.Caption = "Italy!"
Case "Hamburger", "hamburger": lbl1.Caption = "United States of America!"
Case "Maple Syrup", "maple syrup": lbl1.Caption = "Canada!!"
Case else: lbl1.Caption = "Please enter a valid food!"
End Select

As you can see, you save much more time and space to your code!

In Addition

You may also use UCase$ or LCase$ function.

Original code:

Select case txt1.Text
Case "Taco", "taco": lbl1.Caption = "Mexico!"
Case "Perogie", "perogie": lbl1.Caption = "Poland!"
Case "Spaghetti", "spaghetti": lbl1.Caption = "Italy!"
Case "Hamburger", "hamburger": lbl1.Caption = "United States of America!"
Case "Maple Syrup", "maple syrup": lbl1.Caption = "Canada!!"
Case else: lbl1.Caption = "Please enter a valid food!"
End Select

Edited:(For instance you're going to used LCase$ function)
Select case LCase$(txt1.Text)
Case "taco": lbl1.Caption = "Mexico!"
Case "perogie": lbl1.Caption = "Poland!"
Case "spaghetti": lbl1.Caption = "Italy!"
Case "hamburger": lbl1.Caption = "United States of America!"
Case "maple syrup": lbl1.Caption = "Canada!!"
Case else: lbl1.Caption = "Please enter a valid food!"
End Select

Regards,

tobz

answer

it's written in the tut

]
.
.
If txt1.Text = "hamburger" Then lbl1.Text = "United States of America!"
If txt1.Text = "maple Syrup" Then lbl1.Text = "Canada!!"
Else lbl1.Text = "What's that?"
End Sub

"We can do other comparisons

"We can do other comparisons besides just he = statement."

"he" should be replaced by "the".

Great tutorial!

Passing by...

Your article is really very unique view.
From this article I learned a lot.

Macro

I want to set up a macro that will copy a certain 8x8 group of cells with respect to the date. For example if the date equals July 15th, then copy a8 thorugh h8, but when the date changes to July 16th I want the macro to then copy i8 through p8 and so on as the date changes. Maybe I need to use something different than a Macro, but I was instructed to try to use Visual Basics so I thought I would ask. Any help is greatly appreciated.

Thanks

good job

well done, this is way easier for me to learn like this then reading some 1000 page book, i like the pictures, everything is explained good, and easy to read, thanks!

nice article u guys doin

nice article u guys doin great job!!!!!!

New to the Programming

How to become a good programmer. do Math need for the programmers?

REPLY

Of course! It doesn't really matter what language you use, you need math skills. SERIOUS math skills. Lucky me I can read Bianary.

dont tell me that you only

dont tell me that you only knew 0 and 1, lol what a bitch

are you sure?

are you sure?

Just passing by..

you dont really have to put those end if after the statement,because it is not yet complete,,
here check my code:

If TextBox1.Text.Length = 0 Or TextBox2.Text.Length = 0 Or TextBox3.Text.Length = 0 Or TextBox4.Text.Length = 0 Or TextBox5.Text.Length = 0 Or TextBox6.Text.Length = 0 Then
MessageBox.Show("The system will store the new record into the database.")

ElseIf Not IsNumeric(TextBox4.Text) Then
MessageBox.Show("Please enter a numeric Purchase Price")
TextBox4.Focus()
ElseIf Not IsNumeric(TextBox5.Text) Then
MessageBox.Show("Please enter a numeric Sale Price")
TextBox5.Focus()
ElseIf Not IsNumeric(TextBox6.Text) Then
MessageBox.Show("Please enter a numeric Number of items on stock")
TextBox6.Focus()

Else
MessageBox.Show("The system will store the new record into the database.")
Button3.PerformClick()
Label9.Text = Label9.Text + 1

End If

there must be a following "elseif" and "else" statement to support your command,,

and that's it,,if you have anymore questions just mail me at me "jhoricbea@yahoo.com" but dont ask me about classes coz i'm having a hard time explaining how it works,,dont get me wrong as expert on vb6 coz i'm just 14,,,lol,,but i dunno alot of things about computer esp. programming,,

VB6

I spent £17.99 on a book called 'Learn VB6 in 24 hours' and it was hopeless. I could not follow the examples because it was too advanced and the software prorgam included did not open. You tutorials are so good and so clear I am loving them. Great stuff I can't wait to try out more examples

Not because of the book is

Not because of the book is hopeless but you

Thanks.

I read the replies to those questions the people before had and got some good tips.

about statement-end if

i was making an simple prog of getting log of number.i that i wrote
if val(txt1.text)<=0 then lbl1.text="not defined"
If Val(txt1.Text) > 0 Then lbl1.Caption = Log(Val(txt1.Text))

here i used end if ,and programme failed to execute.but when i removed it,it got executed smoothly.
here ,why end if is not required?why?

please send answer on email address 'miku1990_k@yahoo.com'

thank you

When to use end if

if I am understanding you correctly your code looks like this:
if val(txt1.text)<=0 then lbl1.text="not defined"
If Val(txt1.Text) > 0 Then lbl1.Caption = Log(Val(txt1.Text))
End If

The error occurs on line 3 with the end if. This is because you put the entire if then clause on one line. When you need to use end if is if you take it to a new line. For example:
if val(txt1.text)<=0 then 
    lbl1.text="not defined"
End if
If Val(txt1.Text) > 0 Then 
    lbl1.Caption = Log(Val(txt1.Text))
End If

Notice how I am using multiple lines for my if then statement.

Error

my code is like this:

Private Sub Command1_Click()
Dim var1 As Integer
var1 = 10
If var1 = 10 Then
MsgBox
End If
End Sub<code>
 
But when i run the program an error message says: <cite>Compile error: Argument not optional<cite>
And then VB highlitght <strong><code>Private Sub Command1_Click()<code><strong>

Please, go to study

Please, go to study

U must give any message in d

U must give any message in d MsgBox syntax like MsgBox"hi "

thats because at the end u

thats because at the end u just put MsgBox where as it should be

MsgBox "This is not 10"

if and else operators

you must add an argument in the MsgBox so as to run you program