Getting Started Visual Basic
Getting Started Visual Basic
Getting Started Visual Basic
• start VB
• A New Project window will appear. Select Standard.exe and click on Open.
• Go to the Project menu and click Add Module
• Copy the subroutine into the module.
• Go to the Project menu again and click the Properties entry (should be last item in the
menu).
• In the dialog box you should find a combo box called Startup Object, click there and
choose Sub Main
• On the View menu click Immediate Window or press Control-G, a window should open at
the bottom of the VB IDE. this is usually known as the Debug Window
• Go to the Run menu and click Start with Full Compile. VB might ask if you want to save,
just say no this time.
You should see the words Hello World! printed in the Immediate Window
One of the first things you'll want to learn is the use of picture boxes and the print command.
To make a picture box, just select its icon from the tool bar and click and drag one into existence
where you want it to be placed on your form. i.e. click on the form, and drag on the form.
The print command is used primarily with picture boxes. It is a simple way to give the user
output. Output can be given to the user at any time during the running of the program.
Before a print command runs, however, it needs something to trigger it to run, eg, clicking on a
command button.
A command button is just like a picture box: after selecting its button in the tool box, just click
and drag one to where you would like the command button to be placed on your form.
After creating a command button, place code inside the button, by double clicking it, to bring up
a white screen, which has some text on it.
Oagilwe Nokaneng 1
You should see something that says "Private sub command1_click()" and then lower see some
text saying "End Sub".
Any (additional) code you put between those lines will run each time the command button is
clicked.
Now, for the print command. Simply type picture1.print "Your message here". The picture1
refers to what object you are printing on, which is the default name for a picture box.
You can change the name of your picture box, but that will be covered later. Print is the
command, but this does NOT involve a printer. It merely prints something on the screen. And the
text in quotes is whatever you want your message to be.
You will need to go back to the Project menu and select Project1 Properties and select Form1 in
the Startup Object drop down box which was changed in the first example.
Congratulations, you've made your first program. To test it, press the run button at the top of
your screen. It looks like a 'Play' button on a VCR, and should be next to a "Pause" symbol.
Your form should pop up onto your screen, but this time when you click the command button,
the code will run.
In the picture box you should see your message. If an error message appears, check your syntax
or check the error guide. If you're still confused, read the printing section.
Control Properties
To display the Control Properties window, select View\Properties Window or press the F4 key.
The Properties window initially appears on the right edge of the main window (see screen shot.)
Components
A component is an executable module stored either as a VBX file (for the 16-bit versions of VB)
or as a Dynamic Link Library (DLL) file with the extension .OCX, which can be used by others
without knowledge or understanding of the details of its inner workings. Small Text
Oagilwe Nokaneng 2
Events
An event is an activity that occurs during a program's execution, such as a mouse click or a
keystroke. An event causes a procedure to execute. You the programmer can decide what code
you want to place within the procedure.
Forms
A form is a window where controls are placed upon. The .Caption property changes the title of
the window, and .MinBox and .MaxBox show or hide the minimize and maximize buttons.
Typing in with this is the FormBorderStyle property which determines whether the window can
be resized or whether it has a title-bar. It is a good idea to name a form with frm<FormName>.
Buttons
A button will be your best friend in Visual Basic. Each button should contain code, which is
added by you, the programmer. Upon clicking the button, the user will be instructing the
program to execute that portion of code. For example, you could set it so when pressed, the
program will make a message box that says "HELLO!". Good programming styles generally use
cmd<ButtonName> when naming a button.
Text boxes
Text boxes allows the users to add text areas to their programs. This text does not have to be
typed in directly by the programmer, but could come from other sources such as database fields,
text files or data the user will type in while the program is running. Although the default value
for this is ".Text" it can be set to anything including "" (or nothing). Text boxes are usually
denoted with txt<BoxName>.
Labels
Labels are one of the most used Visual Basic objects. They are often used to label other controls
(textboxes, images etc) or provide feedback to the user. They are usually marked with
lbl<LabelName>.
Timers
Timers are interesting and easy to learn. If you want the program to perform a certain task after a
certain amount of time, the Timer is there to help you out. Their only event procedure is _timer,
which will be executed every time after a certain amount of time is passed. The most common
steps to use Timers is as simple as follows:
1. draw a timer and give it a name.
2. set the time interval.
3. double click the timer and write down what you want it to do.
Oagilwe Nokaneng 3
Timers have very few properties too.
This is a possible use of timer:
Timer1.Enabled = True
Shape1.Visible = False
End Sub
Shape1.Visible = True
Timer1.Enabled = False
End Sub
This would make a shape disappear when the start button is pressed, then reappear after the
interval is set in the timer's properties. Here is a timer Clock code:
'***************************************************************** *
'APRON TUTORIAL PRESENTED BY MORROWLAND *
'***************************************************************** *
'Project Name : Timer * * Project Description : Using Timer and
'Counter * * Project Type : Visual Basic * * Author : Ronny André
'Reierstad * * Web Page : www.morrowland.com * * E-Mail :
'apron@morrowland.com * * Version : English (UK) * * Date :
'27.06.2002 *
'*****************************************************************
'Timers are the backbone in any good application, you will be able
'to decide when things will happen in millisecounds by using timers
'and counters you gain control
Oagilwe Nokaneng 4
'The timer procedure
'the timer procedure will loop in the interval of the timer
'I have set the timer interval in the "properties" menu to 1000 ms (1 sec)
Private Sub Timer1_Timer()
End Sub
Picture boxes
Although called picture boxes, these objects are not just a heavyweight version of image boxes:
picture boxes almost have the same properties and function as Form objects. It can do far more
than just displaying pictures. Probably the best way to describe picture boxes is that they are
containers that can group other objects together, kind of similar to frame objects. E.g. several
command buttons can be drawn "inside" of it.
General properties
General properties depend on the Object in question. Common properties include: Name, which
is the file name; Background color, self explanatory; and if the object was say a timer this is
where you would set how long it counted. Most general properties can be set at run time.
References
Reference is a kind of link that is used by Visual Basic. The word reference is used in two
distinct ways:
Component reference
this connects your program to external libraries such as DLLs, OCXs, or type library
Object reference
an object reference is a pointer to an object
These two uses are quite distinct and generally do not cause any problems. Usually when object
reference is meant it will be written out in full whereas just references usually means references
to an external library.
You can create components in VB to be used by other programs (not just those written in VB).
Reserved Words
Visual Basic contains several reserved words. These words are "reserved" because they are
specific functions and commands in Visual Basic. For example, a variable may not be named
"Print" because it is a feature in VB to print. This can be avoided however, by naming your
Oagilwe Nokaneng 5
variables "prnt" or "print1". As long as it is not the exact word, it should work. A list of
frequently used reserved words/keywords:
REMs
While programming you may find it necessary to leave yourself notes. This can be used to easily
identify areas of code, or as a reminder of sections of code with logic errors that need to be fixed.
REMs are very simple. Merely place an apostrophe, " ' ", or the word, "REM", before the line
and that line will be ignored by the interpreter, whether it be a message to yourself or a section of
code. For example:
An apostrophe is most often used due to the comparative reduction in space and time. "REM"'s
will almost work in exactly the same way as the apostrophe, except that a "REM" must be placed
at the beginning of a line, while the apostrophe can go anywhere:
Error Checking
These are several common types of errors that one might get from a VB program:
run-time errors
This type of error are errors that are raised when the program is running. Examples:
dividing anything by zero or assigning a string to a numeric variable.
compile errors
Compile errors are errors that the IDE spots at design-time and upon compiling the
program just before it runs the program. These errors include syntax errors -- the error
raised when the computer does not understand your code, and also errors like undeclared
variables etc.
logic errors
Logic errors are errors that the computer cannot spot. These are errors that, even though
the program runs, the result is not what you intended.
The first two of these errors are generally easy to spot, and the debugging tool can be used to
high-light the line of text at which the error occurred. For example, if you wanted to make a
program to convert Celsius to Fahrenheit, and in the code you used a multiplication symbol
instead of division, the program would run fine, but the program would not convert the
temperatures correctly, as you desired. Although sometimes these logic errors can be easy to
spot, some are quite difficult. Logic errors become concealed in the lines of code when making
complex programs, such as a game. Just remember, the computer does not know what the
Oagilwe Nokaneng 6
program is supposed to do, it only knows the code. Look through the code step-by-step and think
of how the computer would intepret the code.
VB won't let you just ignore syntax/compile errors. You have to fix them before you can run
your program. But run-time errors, which are syntactically correct, but may cause an error if an
attempt is made to execute it, can be handled to possibly prevent your program from crashing.
The following example shows a very good way of handling a possible error:
The output of this example is a message box that says "Error Number 11: Division by zero". The
statement On Error Goto Label1 will skip everything from i = 1 / 0 to <yy>Exit Sub if any
run-time error occurs within this procedure. And the program will continue to run from right
after Label1:, where the error will be displayed so that the programmer can find out what it is
and fix it. This also prevents the program from "crashing".
Label1 is just a name for a label, you can name it anything you wish although it is good
programming style to denote it with lbl and then the label's given name. Exit Sub means to end
the Form_Load event immediately.
So if no error occurs, a message box will NOT be called because Exit Sub will already have
ended or exited our subroutine. And if an error does occur, the message box will pop up,
displaying the Error Number and the Error Description.
The above example is the safest way of detecting and handling any error that takes place in the
subroutine. However you can also choose to ignore errors by using "On Error Resume Next"
(which means to ignore all errors), and watch for errors in a certain line of code by using "On
Local Error ..."
Oagilwe Nokaneng 7
name and the type of value it will be able to hold (which will be discussed later). To dimension a
variable, the code is:
Of course, the variable name could be whatever you want. The type however, is different. You
have a choice of single, integer, or string. This tells the computer what type of information the
variable holds. "Single" variables can hold numbers with decimal. "Integers" variables can hold
whole numbers, while "String" variables holds text or a set of characters. If you don't dim a
variable, the type would automatically be "Variant", which can hold almost all kinds of
information. For example:
Option Explicit
Dim intNumber As Integer
Dimming is especially important for arrays and matrixes. For an array, next to the variable name,
you enter the range of the array. For example:
Arrays will be covered more in depth later. Matrixes are dimensioned almost exactly like arrays
are, however, instead of the having only one dimension (1 to 20), matrixes may have two: (1 to
20,1 to 5), or even three. Dimensioning can also be used to tell the computer that variables are
public. This will be discussed later in the Scope section.
Note: If you don't dimension your variables, you might end up with many unexpected errors. It
could be avoided by using the Option Explicit statement, which requires every variable to be
defined; if not every variable used in the program is defined, VB raises an error: "Variable is not
defined". To enable this, you just have to type Option Explicit at the very top of ALL your code
in the current module. It's a very good practice to do so.
Simple output
The interaction between the user and the computer consists of both the input and output of data.
The computer will not receive your commands if you don't have a mouse or keyboard which are
used to input commands. And conversely, you wouldn't know what the computer is doing at all if
there is no monitor or speaker which are used to output data. Therefore output is important.
Message boxes
One of the easiest form of output is message box. I'm sure you've seen a lot of message boxes in
Windows. This is what the code of a normal message box should look like.
Oagilwe Nokaneng 8
Try it. Are you tired of the boring "hello world"? Let's make a fancier one:
MsgBox "Fatal error: Your computer will be shut down in five seconds.", vbCritical,
"System"
Printing
Note: The word "printing" here means using the Print statement, it's not about using the printer
or printing files. Printing is a fairly simple part of Visual Basic, but also essential. Printing is
used to output information to the user. It proves to be a valuable troubleshooting tool. Whenever
printing, you need an object to print on, followed by of course, something to print. Printing may
be used with various objects, however, the most common in the picture box. For the sake of
simplicity, we are assuming you renamed the picture box as "pic". In this wikibook though, print
is done mainly on picture boxes and forms:
Spacing
There are various ways to alter how text is spaced when printing. The most common is the
comma. A comma will go to the next print zone. Print zones are 15 characters long. You can
think of it like pressing the tab key when typing something out. Remember that print zones are
fixed, so if you've typed 1 letter, and then used a comma, then it will be a big space. If you type
13 characters and use a comma, it will not be a large space. For example:
Several new concepts are introduced in this example. The "Form_Click" contains a block of code
and it is called to run when the user clicks on the current Form(Form1). 'Me' is the same as the
current form (Form1). Don't be afraid to experiment. No matter what you do in VB, its always
reversible. Now, the comma isn't all that versatile. Another feature is tab. Tab will move so many
spaces from the BEGINNING of the line. Followed by tab in parentheses is the amount of
characters spaces. For example:
This will NOT print "yay" 10 spaces after the O of "Hello". Rather it will print 10 spaces from
the beginning of the line. You may use as many tabs as you want in the same print command.
Although tab is useful, sometimes it is better to space things in relation to what has already been
printed. This is where the space function comes in. The syntax of space is identical to that of tab.
Space will move the next printed text so many spaces over from its CURRENT location. For
example:
Oagilwe Nokaneng 9
Pic.print "Hello"; Space(10); "Yay"
This will print the first Y of "Yay" 10 spaces to the right of the O in "Hello". It is important to
note, if you write:
Pic.Print "Hello"
Pic.Print "Hello"
Hello
Hello
This can be easily dealt with in the need of having separate print statements print on the same
line. You merely have to change the code to: (note the semicolon)
Pic.Print "Hello";
Pic.Print "Hello"
HelloHello
If you want to make a blank line in between the two "hello"'s, then you may simply have a blank
print statement WITHOUT a semicolon. For example:
Pic.Print "Hello"
Pic.Print
Pic.Print "Hello"
Hello
Hello
It is important to remember that if the first print has a semicolon at the end, often referred to as a
trailing semicolon, the empty print will only reverse it, and print the second Hello on the next
line, and no blank line will appear.
Oagilwe Nokaneng 10
Reserved words are words that have special meaning to Visual Basic.
Visual basic has 177 words that are special words, and are reserved for Visual
Basic only. In other words you cannot use
any of these words as names for variables, properties or methods, etc.
It would be a good idea to familiarize yourself with this list of reserved words.
It's not necessary that you try to
memorize them, because the Visual Basic compiler will display an error if you
attempt to use them as names.
All of these Identifiers can be found in the Visual Basic Help, under "reserved
keywords"
I don't know C++ rules. I assume the same rules and more apply?
foo_
m_foo
_foo
Sarath
Posts: n/a
Oagilwe Nokaneng 12
In the case of member variables are _ prefixes still reserved?
Seems it is allowed.
Please refer
http://www.cplusplus.com/doc/tutorial/variables.html
Regards,
Sarath
http://sarathc@wordpress.com/
Posts: n/a
Ian Collins
#3: Mar 23 '07
Sarath wrote:
>>I know C's rules about reserved identifiers (anything starting with
>>"_", leading "is", etc).
>>
>>I don't know C++ rules. I assume the same rules and more apply?
>>
>>I've seen several conventions for member variables:
>>
>>foo_
>>m_foo
>>_foo
>>
>>In the case of member variables are _ prefixes still reserved?
>
Seems it is allowed.
>
Please refer
http://www.cplusplus.com/doc/tutorial/variables.html
>
Oagilwe Nokaneng 13
Each name that begins with an underscore is reserved to the
implementation for use as a name in the global namespace.
--
Ian Collins.
=?iso-8859-1?q?Erik_Wikstr=F6m?=
Posts: n/a
--
Erik Wikström
Posts: n/a
Greg Herlihy
Oagilwe Nokaneng 14
#5: Mar 23 '07
Sarath wrote:
>>I know C's rules about reserved identifiers (anything starting with
>>"_", leading "is", etc).
>>>
>>I don't know C++ rules. I assume the same rules and more apply?
>>>
>>I've seen several conventions for member variables:
>>>
>>foo_
>>m_foo
>>_foo
>>>
>>In the case of member variables are _ prefixes still reserved?
>>
>Seems it is allowed.
>>
>Please refer
>http://www.cplusplus.com/doc/tutorial/variables.html
>>
In other words, names that begin with a leading underscore and that are not
in the global namespace are available as names for the program to use. And
since the names of member variables are names in the scope of the class that
defines them - they are not names in the global namespace itself. So a
Oagilwe Nokaneng 15
program is free to use a name with a (single) leading underscore as the name
of a class member. Nevertheless, to keep things simple it is probably a good
idea for a program not to use a name with a leading underscore anywhere -
even when it may be OK to do so.
Greg
Gavin Deane
Posts: n/a
Sarath wrote:
>
>I know C's rules about reserved identifiers (anything starting with
>"_", leading "is", etc).
>
>I don't know C++ rules. I assume the same rules and more apply?
>
>
>foo_
>m_foo
>_foo
Oagilwe Nokaneng 16
>
>
Seems it is allowed.
>
Please refer
>http://www.cplusplus.com/doc/tutorial/variables.html
>
>
>
In other words, names that begin with a leading underscore and that are not
in the global namespace are available as names for the program to use. And
since the names of member variables are names in the scope of the class that
defines them - they are not names in the global namespace itself. So a
program is free to use a name with a (single) leading underscore as the name
of a class member.
Agreed. And the same for names containing a double underscore. I know
what the rules are and I know where to look them up to remind myself
if I forget (mainly because this question arises here every so often).
Oagilwe Nokaneng 17
But I see no advantage in demonstrating in code how clever I am by
allowing myself to use leading underscores where they are legal. Far
simpler to just avoid leading underscores and double underscores
completely (and I don't find that restriction causes me any difficulty
at all).
Gavin Deane
Posts: n/a
Marcus Kwok
#7: Mar 23 '07
Tim H <thockin@gmail.comwrote:
--
Marcus Kwok
Replace 'invalid' with 'net' to reply
red floyd
Posts: n/a
Oagilwe Nokaneng 18
re: reserved identifiers?
>I know C's rules about reserved identifiers (anything starting with
>"_", leading "is", etc).
>>
>I don't know C++ rules. I assume the same rules and more apply?
>>
>I've seen several conventions for member variables:
>>
>foo_
>m_foo
>_foo
>>
>In the case of member variables are _ prefixes still reserved?
>
Any name beginning with a double underscore or an underscore followed
by an uppercase letter is reserved for any use, in short, don't use.
Any name beginning with an underscore is reserved for use in the
global namespace, meaning be careful.
Posts: n/a
red floyd
#9: Mar 23 '07
>>I know C's rules about reserved identifiers (anything starting with
>>"_", leading "is", etc).
>>>
>>I don't know C++ rules. I assume the same rules and more apply?
>>>
Oagilwe Nokaneng 19
>>I've seen several conventions for member variables:
>>>
>>foo_
>>m_foo
>>_foo
>>>
>>In the case of member variables are _ prefixes still reserved?
>>
>Any name beginning with a double underscore or an underscore followed
>by an uppercase letter is reserved for any use, in short, don't use.
>Any name beginning with an underscore is reserved for use in the
>global namespace, meaning be careful.
>
Also according to 17.3.4.1.2/2 footnote 165, leading underscore
identifiers are reserved in the std:: namespace as well.
Oagilwe Nokaneng 20