Vous êtes sur la page 1sur 6

The Visual Basic Language: Operators, Conditionals, and

Loops

Visual Basic Statements

Nothing for all reference types (including Object, String, and all
arrays). Nothing means there is no object associated with the
reference.
False for Boolean.
12:00 AM of January 1 of the year 1 for Date.

A Visual Basic statement is a complete instruction. It can contain:

Variable Prefixes
Keywords Words reserved for Visual Basic's use.
Operators Symbols used to perform operations, like +, which
performs addition operations; -, which performs subtraction
operations; and so on.
Variables Symbolic names given to values stored in memory and
declared with the Dim keyword. For example, if you've declared a
variable named temperature as an Integer type, you can store
integer values like 72 or 83 in it.
Literal values Simple values, like 5 or "Hello."
Constants The same as variables, except that constants are
assigned a value that cannot then be altered.
Expressions Combinations of terms and/or keywords that yield a
value. For example, if the variable temperature holds the value 72,
then the expression temperature + 3 yields the value 75.

Data type
Boolean
Byte
Collection object
Date (Time)
Double
Error
Integer
Long
Object
Single
String
User-defined type

Declaring Variables

Visual Basic Data Types

You need to store some data in your program so you need to declare
some variables. You must declare all variables before using them by default
in VB .NET, and you can do that with the Dim statement (which originally
stood for dimension, as when you set the dimensions of an array); this
statement is used at module, class, structure, procedure, or block level:

Type
Boolean
Byte
Char
Date
Decimal

Storage size
2 bytes
1 byte
2 bytes
8 bytes
16 bytes

Dim EmployeeID As Integer = 1


Dim EmployeeName As String = "Bob Owens"
Dim EmployeeAddress As String

Double

8 bytes

Visual Basic will initialize it to a default value for its data type:

Integer
Long

4 bytes
8 bytes

Object

4 bytes

[ <attrlist> ] [{ Public | Protected | Friend | Protected


Friend | Private | Static }] [ Shared ] [ Shadows ]
[ ReadOnly ] Dim [ WithEvents ]
name[ (boundlist) ] [ As [ New ] type ] [ = initexpr ]

0 for all numeric types (including Byte).


Binary 0 for Char.

Prefix
bln
byt
col
dtm
dbl
err
int
lng
obj
sng
str
udt

Value range
True or False
0 to 255 (unsigned)
0 to 65535 (unsigned)
January 1, 0001 to December 31, 9999
+/-79,228,162,514,264,337,593,543,950,335
with no decimal point; 7.92281625142643
37593543950335 with 28 places to the right of
the decimal; smallest non-zero number is
0.00000 00000000000000000000001
-1.79769313486231E+308
to
-4.94065645841247E-324 for negative values;
4.94065645841247E-324
to
1.79769313486231E+308 for positive values
-2,147,483,648 to 2,147,483,647
-9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
Any type can be stored in a variable of type
Object
Source: Visual Basic .NET Black Book
by Steven Holzner

Short
Single

2 bytes
4 bytes

String

Depends on
implementing
platform
Sum of the sizes of its members. Each member of the structure
has a range
determined by its data type and independent of the ranges of
the other members

UserDefined
Type
(structure)

-32,768 to 32,767
-3.402823E to -1.401298E-45 for negative
values; 1.401298E-45 to 3.402823E for
positive values
0 to approximately 2 billion Unicode characters

Data Conversion Functions


To convert
Character code to
character
String to lowercase or
uppercase
Date to a number
Decimal number to
other bases
Number to string
One data type to
another
Character
to
character code
String to number
Time to serial number

Use this
Chr
Format,
LCase,
UCase,
String.ToLower, String.Format
DateSerial, DateValue
Hex, Oct

String.ToUpper,

Format, Str
CBool, CByte, CDate, CDbl, CDec, CInt, CLng,
CObj, CSng, CShort, CStr, Fix, Int
Asc
Val
TimeSerial, TimeValue

To do this
Concatenate
two
strings
Compare two strings
Convert strings
Copying strings
Convert to lowercase
or uppercase
Convert to and from
numbers
Create string of a
repeating character
Create an array of
strings from one string
Find length of a string
Format a string
Get a substring
Insert a substring
Justify a string with
padding
Manipulate strings
Remove text
Replace text
Set string comparison
rules
Search strings

Type Checking Functions


Function
IsArray()
IsDate()
IsDBNull()
IsError()
IsNumeric()
IsReference()

Does this
Returns True if passed an array
Returns True if passed a date
Returns True if passed a database NULL value; that is, a
System.DBNull value
Returns True if passed an error value
Returns True if passed an numeric value
Returns True if passed an Object variable that has no
object assigned to it; otherwise, returns False

String-handling Functions and Methods

Trim leading or trailing


spaces
Work with character
codes

Use this
&, +, String.Concat, String.Join
StrComp,
String.Compare,
String.Equals,
String.CompareTo
StrConv, CStr, String. ToString
=, String.Copy
Format, Lcase, Ucase, String.Format, String.
ToUpper, String. ToLower
Str, Val.Format, String.Format
Space, String, String.String
String.Split
Len, String.Length
Format, String.Format
Mid, String.SubString
String.Insert
LSet, Rset, String.PadLeft, String.PadRight
InStr, Left, LTrim, Mid, Right, RTrim, Trim,
String.Trim, String.TrimEnd, String.TrimStart
Mid, String.Remove
Mid, String.Replace
Option Compare
InStr,
String.Chars,
String.IndexOf,
String.IndexOfAny,
String.LastIndexOf,
String.LastIndexOf Any
LTrim, RTrim, Trim, String.Trim, String.TrimEnd,
String.TrimStart
Asc, AscW, Chr

Visual Basic Operators


Source: Visual Basic .NET Black Book
by Steven Holzner

Arithmetic operators

^ Exponentiation

* Multiplication

/ Division

\ Integer division

Mod Modulus

+ Addition

- Subtraction
Assignment operators

= Assignment

^= Exponentiation followed by assignment

*= Multiplication followed by assignment

/= Division followed by assignment

\= Integer division followed by assignment

+= Addition followed by assignment

-= Subtraction followed by assignment

&= Concatenation followed by assignment


Comparison operators

< (Less than)True if operand1 is less than operand2

<= (Less than or equal to)True if operand1 is less than or equal to


operand2

> (Greater than)True if operand1 is greater than operand2

>= (Greater than or equal to)True if operand1 is greater than or


equal to operand2

= (Equal to)True if operand1 equals operand2

<> (Not equal to)True if operand1 is not equal to operand2

IsTrue if two object references refer to the same object

LikePerforms string pattern matching


Visual Basic Operator Precedence
1. The Arithmetic operators have the highest precedence:

Exponentiation (^)

Negation (-) (for example, - intValue reverses the


sign of the value in intValue)

Multiplication and division (*, /)

Integer division (\)

Modulus arithmetic (Mod)

Addition and subtraction (+,-)


2. Concatenation operators:

String concatenation (+)

String concatenation (&)


3. Comparison operators

Equality (=)

Inequality (<>)

Less than, greater than (<,>)

Greater than or equal to (>=)

Less than or equal to (<=)

Like

Is
4. Logical/Bitwise operators

Negation-(Not)

Conjunction-(And,AndAlso)

Disjunction-(Or, OrElse, Xor)


Making Decisions with IfElse Statements
How can you make choices in your code, deciding what to do next depending
on the values in your variables? You can use the If statement, which is the
bread-and-butter of Visual Basic conditionals, and which lets you evaluate
your data and execute appropriate code.
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements] ]
[Else
[elsestatements]]
End If
You use comparison operators in the condition here to generate a logical
result that's true or false.
If condition is True, the statements immediately following the Then keyword
in the body of the If statement will be executed, and the If statement will
terminate before the code in any ElseIf or Else statement is executed. If
condition is False, the following ElseIf statements are evaluated, if there are
any; this statement lets you test additional conditions, and if any are True, the
corresponding code (elseifstatements above) is executed and the If
Source: Visual Basic .NET Black Book
by Steven Holzner

System.Console.WriteLine("OK.")
Case 4 To 7
System.Console.WriteLine("In the range 4 to 7.")
Case Is > 7
System.Console.WriteLine("Definitely too big.")
Case Else
System.Console.WriteLine("Not a number I know.")
End Select

statement terminates. If there are no ElseIf statements, or if none of their


conditions are True, the code in the Else statement, if there is one, is
executed automatically.
Dim intInput As Integer
System.Console.WriteLine("Enter an integer")
intInput = Val(System.Console.ReadLine())
If intInput = 1 Then
System.Console.WriteLine("Thank you.")
ElseIf intInput = 2 Then
System.Console.WriteLine("That's fine.")
ElseIf intInput = 3 Then
System.Console.WriteLine("Too big.")
Else
System.Console.WriteLine("Not a number I know.")
End If
Select Case
If your program can handle multiple values of a particular variable and you
don't want to stack up a lot of If Else statements to handle them, you should
consider Select Case. You use Select Case to test an expression, determine
which of several cases it matches, and execute the corresponding code.
Select Case testexpression
[Case expressionlist-n
[statements-n]]
[Case Else
[elsestatements]]
End Select
You use multiple Case statements in a Select statement, each specifying a
different value to test against textexpression, and the code in the Case
statement that matches is executed.
Dim intInput As Integer
System.Console.WriteLine("Enter an integer")
intInput = Val(System.Console.ReadLine())
Select Case intInput
Case 1
System.Console.WriteLine("Thank you.")
Case 2
System.Console.WriteLine("That's fine.")
Case 3

Do Loop
The Do loop keeps executing its enclosed statements while or until
(depending on which keyword you use, While or Until) condition is true. You
can also terminate a Do loop at any time with an Exit Do statement.
Do [{While | Until} condition ]
[statements]
[Exit Do]
[statements]
Loop
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
Dim strInput As String
Do Until UCase(strInput) = "STOP"
System.Console.WriteLine("What should I do?")
strInput = System.Console.ReadLine()
Loop
For Loop
The For loop is probably the most popular of all Visual Basic loops. The Do
loop doesn't need a loop index, but the For loop does; a loop index counts
the number of loop iterations as the loop executes.
For index = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [index]
Source: Visual Basic .NET Black Book
by Steven Holzner

The index variable is originally set to start automatically when the loop
begins. Each time through the loop, index is incremented by step (step is set
to a default of 1 if you don't specify a value) and when index equals end, the
loop ends.
Dim intLoopIndex As Integer
For intLoopIndex = 0 To 3
System.Console.WriteLine("Hello from Visual Basic")
Next intLoopIndex

Dim intCounter As Integer = 0


Dim intNumber As Integer = 10
While intNumber > 6
intNumber -= 1
intCounter += 1
End While
With Statement

For EachNext Loop

The With statement is not a loop, properly speaking, but it can be as useful
as a loopand in fact, many programmers actually think of it as a loop. You
use the With statement to execute statements using a particular object.

You use the For EachNext loop to loop over elements in an array or a
Visual Basic collection. This loop is great, because it automatically loops over
all the elements in the array or collectionyou don't have to worry about
getting the loop indices just right to make sure you get all elements, as you
do with a For loop.

With object
[statements]
End With

For Each element In group


[statements]
[Exit For]
[statements]
Next [element]
Dim intIDArray(3), intArrayItem As Integer
intIDArray(0) = 0
intIDArray(1) = 1
intIDArray(2) = 2
intIDArray(3) = 3
For Each intArrayItem In intIDArray
System.Console.WriteLine(intArrayItem)
Next intArrayItem
While Loop
While loops keep looping while the condition they test remains true, so you
use a While loop if you have a condition that will become false when you
want to stop looping.

With TextBox1
.Height = 1000
.Width = 3000
.Text = "Welcome to Visual Basic"
End With
Handling Dates and Times
One of the biggest headaches a programmer can have is working with dates.
Handling hours, minutes, and seconds can be as bad as working with
shillings, pence, and pounds.
Visual Basic Date and Time Properties
Get the current date or
time
Perform date calculations
Return a date
Return a time
Set the date or time
Time a process

Today, Now, TimeofDay, DateString,


TimeString
DateAdd, DateDiff, DatePart
DateSerial, DateValue
TimeSerial, TimeValue
Today, TimeofDay
Timer

While condition
[statements]
End While
Source: Visual Basic .NET Black Book
by Steven Holzner

The Format function makes it easy to format dates into strings, including
times.
Format Expression
Format(Now, "M-d-yy")
Format(Now, "M/d/yy")
Format(Now, "MM - dd - yy")
Format(Now, "ddd, MMMM d, yyy")
Format(Now, "d MMM, yyy")
Format(Now, "hh:mm:ss MM/dd/yy")
Format(Now, "hh:mm:ss tt MM-dd-yy")

Yields this
"1-1-03"
"1/1/03"
"01 /01 / 03"
"Friday, January 1, 2003"
"1 Jan, 2003"
"01:00:00 01/01/03"
"01:00:00 AM 01-01-03"

Source: Visual Basic .NET Black Book


by Steven Holzner

Vous aimerez peut-être aussi