VB Statements – Dim, if, decimal.tryparse, exit sub, writealltext

Index

 WriteAllText Method

  • Use the WriteAllText method to write text to a file, specifying the file and text to be written. This example writes the line “This is new text.” to the file named test.txt, appending the text to any existing text in the file.

    My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt",
    "This is new text to be added.",True)

Limitations: The target folder must exist or this statement will result in an error. E.g. “C:\TestFolder” must exist. The file does not have to exist, it will be created.

Dim Statement

Many people have a lot of difficulty with the dim statement so I explain it here:

Dim statements set aside storage for variables. A better word for dim would be “declare”. A dim statement “declares” a variable. Dim statements also tell the computer what kind of variable you are using.

Controls do not need dim statements. When you reference a property of a control (usually the text property)  in code view, you don’t need to dim the property in order to access it. For example:

In design view, you create a textbox and name it tbxN1. The “text” property of the text box is accessed by entering:

tbxN1.text

in code view. The property tbxN1.text is treated as a string variable in the program and does not have to be declared using a dim statement. You get to use all properties of all the controls in your program without declaring them with dim statements.

All other variables need to be declared in dim statements at the beginning of your program. The dim statement looks like this:

Dim v1,v2,v3 as {type}

Where v1,v2,v3 can be any number of variable names, separated by commas, and {type} is the type of variable it is. We use 3 types of variables in this class (there are more).

Decimal – holds a number
String – holds a character string
Boolean – holds a truth value (true or false)

 Here are some examples:

Dim decN1,decN2,decProduct as decimal
(declares three variables as variables which will hold numbers)

Dim strName,strAddress as string
(declares two variables as character strings)

Dim flgSuccess as boolean
(declares a variable as boolean, which will be true or false)

Design

It is a good idea to figure out the variables you need before you start writing code.

Vb If Statement

The If-then Statement

A simplified form of the If statement, which will work for our class, looks like this:

If (cond) then
 {code}
Endif

Two parts of this require explaining.
(cond) is any expression which can be evaluated as true or false.

if (a=3) then

(a=3)  is true or false. So the code:

a=3
 If (a=3) then
    Msgbox("a is indeed 3")
 Endif

Will result in the msgbox being displayed, and:

a=2
If (a=3) then
   Msgbox("a is indeed 3")
Endif

Will result in no msgbox being displayed.
(cond) may also be a boolean variable, as in:

Dim flgSuccess as boolean
flgSuccess = true
If (flgSuccess) then
   Msgbox("flgsuccess is indeed true")
Endif

Will cause the msgbox to display.

Dim flgSuccess as boolean
flgSuccess = false
If (flgSuccess) then
Msgbox(“flgsuccess is indeed true”)
Endif

Will not display the messagebox.

The If-then-else statement

The if statement can be expanded to include an “else” clause. The else clause is taken when the if clause is not true – just like in English.

a=3
If (a=3) then
 Msgbox("a is indeed 3")
Else
  Msgbox("a is not 3")
Endif

Will result in the msgbox “a is indeed 3” being displayed, and

a=2
If (a=3) then
   msgbox("a is indeed 3")
Else
   msgbox("a is not 3")
Endif

Will result in the msgbox “a is not 3” being displayed.

Exit Sub

If you are programming an event, and you want to leave the event, and go back to the screen without executing any more of the event code, exit sub is a handy command. Exit sub is short for “exit subroutine”. A subroutine is what you are in when you are programming an event. Exit sub lets you do things like this:

(check an input for errors and set an error condition)
If (error condition) then
       msgbox("this is an error")
       exit sub
endif
(more code here which will not be executed if the exit sub is run)

This will print the error message and then leave the subroutine, usually to go back to your window in order to correct the problem.

Decimal.tryparse

The visual basic function decimal.tryparse statement is a complicated, but useful, function.

Why you need it:

You use the textbox control to get input into your basic program. In code view, you access the input by referring to the “text” property of the textbox control. For example, say you have a textbox named “textbox1”, the visual basic statement:

a = textbox1.text

Would put whatever the user had entered into the textbox, into the variable a.

If you think about it, you will realize that textbox1.text must be a string variable. It’s no good making it a decimal variable, since the user can enter anything into the textbox. Perhaps you want the user to enter a number, but the user may make a mistake and enter a letter, or a blank. So, textbox1.text is a string variable. If you want to do any math with the contents of textbox1.text, first you must convert it to an appropriate numeric variable, then do the math. So, our program might look like this:

Dim a as decimal ‘ create a variable a which will hold a number

A = textbox1.text

This will work fine if the user entered a number into the textbox. Visual basic knows that A is a numeric variable and is smart enough to convert the string value in textbox1.text into a number.
But what if the user did not enter a number into the textbox? Then, visual basic fails at converting textbox1.text into a number, displays an ugly error message, and stops.

This is where decimal.tryparse is used. Decimail.tryparse tries to convert a character string variable to a numeric variable. If it succeeds, fine, the numeric value of the character string is assigned to the numeric variable. The code looks like this:

Dim a as decimal ‘ this is a numeric variable which will hold a number

Dim success as boolean ‘ true if conversion works, false if it fails

Success = decimal.tryparse(textbox1.text,a)

Decimal.tryparse looks at the character string textbox1.text, and tries to convert it to a number. If it succeeds, then it sets success to true, and a to the value the user entered in the textbox. If it fails, then it sets success to false and it sets the variable a to zero.
You go on in your program to test the value of success. If success is false, you can give the user a nice error message like “please enter a number here”. If success is true, then you go on with your program.
This little chart shows what happens when you enter different things in your text box:

Entry Textbox1.text A Success
123 123 123 True
Null Null 0 False
0 0 0 True
Hello Hello 0 False
-10 -10 -10 true

A common mistake

Decmal.tryparse does two things for you. The first, is that it test whether a text field can be converted to a number. The second is that it converts the text in the text field to a decimal numeric variable. After you use decimal .tryparse, make sure you use the converted field (A in the example above) for all your numeric operations.

How do you know that you know this?

Here’s the same chart, but the values of A and Success are blank. You should be able to fill them in.

Entry Textbox1.text A Success
123 123
Null Null
0 0
Hello Hello
-10 -10

 

Arrays

We have another kind of variable other than the three you’ve used already. The easiest way to explain this is with an example:

Let’s say you had 4 students in your class and they all take a test. You would want to store their test results in a variable. With what you know now, you would have to do something like this:

dim decScore1, decScore2, decScore3, decScore4 as Decimal

Gets to be a lot of typing. And, what do you do when you have 20 scores? Do you just make as many declarations as you possibly need, all in advance?

No. You use an array.

your declaration looks like this:

Dim decScore() as decimal

Note the parentheses. They make a big difference. Now you can write things like this:

decScore(0) = 95
decScore(1) = 80
decScore(2) = 61
decScore(3) = 84

Note that the first element in an array is element zero.

UBound

Ubound(decScores) will return the upper number of the elements in the array.

In our array of decScore, which contains 4 elements, UBound(decScore) will be 4. Remember, the first one is zero, which throws off the count.

Loops

Here are some resources which will help you with this project:
Youtube explaining do while loops:
http://www.youtube.com/watch?v=mdP5mQmAXwg
You tube explaining for loops:
http://www.youtube.com/watch?v=qRJGdPa9X24
Text and tutorials explaining visual basic loops
http://www.go4expert.com/articles/looping-visual-basic-t3696/
http://msdn.microsoft.com/en-us/library/eked04a7.aspx
http://www.dotnetperls.com/for-vbnet

Tutorials on visual basic programming are common on the web. For more on loops,  Google “vb loops”.

Do while syntax (simplified)
Do { While | Until } condition
[ statements ]
[ statements ]
Loop

For Next syntax (simplified)

For counter = start To end
[ statements ]
Next [ counter ]