Beginners Tutorial
This tutorial is intended as a guide for people new to Visual Basic.
It shows common coding conventions and basic use of VB.
==============================================
1. Option Explicit
2. Code Formatting
3. Commenting
4. Variable Types
5. Static Variables
6. Global/Local Variables
7. Public/Private Functions
8. Arrays
9. Constants
10. Control Names
11. Variable/Constant/Procedure Names
==================================
NB: The zip file has the HTML file of the tutorial.
Original Author: JoshD
Code
Beginners Tutorial The tutorial is targeted at users who are new to Visual Basic and provides Like many people I am sick of downloading a program to see that the code is Private Sub Command4_Click() This tutorial forms a guide on how to write your code to look professional. Syntax: 1. Option Explicit Option Explicit (top) Option Explicit is an extremely useful function of VB, if you refer to a variable Dim myName as String If Option Explicit is used VB will stop when the While this mistake appears obvious, and would be easy to debug, when thousands The Option Explicit keywords should be the topmost Code Formatting (top) The most important aspect when writing code for your programs is the format Inside a procedure code will be should indented one tab. Public Sub cmdAbout_Click() For each IF statement, FOR Public Sub cmdDisplay_Click() This is far easier to read than Public Sub cmdDisplay_Click() Note: vbTab adds a tab VB does not insert a Tab character, instead it will insert spaces that act Commenting (top) A comment is a piece of text in your program that is not intended to be executed Commenting is very useful to remind yourself what code does and is very important If submitting a program to PSC, a good idea is to add your name, e-mail, the '**************************************** Comments should be used within the code to explain its function. Dim leap as Boolean If a line of code is long it may be easier to write the comment before the Dim leap as Boolean It is recommended that you do not over comment this can make code appear cluttered Dim leap as Boolean, year as Integer Note: Val(text) will give Use your own judgment whether code needs to be commented, keeping in mind whether Variable Types (top) Visual Basic has the following variable types: String, Integer and Boolean are the most common, but as your programs become A variable is declared as such: Dim var as Boolean If you wish to use this variable in other modules/forms declare it as public: Public var as Boolean A variable that is not given a type becomes a variant by default. Do not do Dim var To save space/time variables can be defined in a single line. Dim var as Boolean, personName as String, age as Integer, siblings Do not declare them in the following fashion Dim var1, var2, var3 as Boolean var1 and var2 will become Static Variables (top) If the keyword Static is used in place of Dim Private Sub cmdCount_Click() The first time the button is pressed (the procedure is run) a message box will Private Sub cmdCount_Click() The count would be re-created each time, and it would revert to 0, therefore Static variables cannot be global, i.e. they should only exist within procedures. Global/Local Variables (top) A variable can be either declared locally or globally. A local variable is frmMain: Dim myName as Stirng 'Global Private Sub cmdRecord_Click() Private Sub cmdDisplay_Click() modChecks: Public message as string 'Public Public Sub CheckMaximum() Notice frmMain.peopleCount is used in CheckMaximum when referring to the variable. Public/Private Functions (top) Similar rules to these apply to procedures. Private procedures can only be GENERAL RULE: If a variable, procedure is used in more than one form it should Arrays (top) An array or variables is useful when you need to store values that belong in Dim name(1 to 100) as String An array can also be declared like so: Dim name(100) as String This would equate to: Dim name(0 to 100) as String In most cases when using arrays the list begins at 0, not 1. The same rules regarding the Public keyword apply, except for two changes: It is possible to define an array without specifying a length: Dim userName() as String In this case the length must be specified lasted using ReDim. This will allow Dim userName() as String An array like those above represent a single dimension. It is possible to have Multi-dimensional arrays are declared in the following fashion: Dim userName(1 To 10, 1 To 10) as String or Dim userName() as String Public Sub SetDimensions() Constants (top) Constants provide an easy way to remember reoccurring numbers or text without Const PI = 3.141592653589 A constant can only be global. A public constant can only be declared in a Public Const PI = 3.141592653589 Visual Basic constants Visual Basic has its own inbuilt constants. Each only begins with the prefix Control Names (top) Naming controls is an important part of programming. It should be done as each Label By doing this your code will be far easier to interpret, a control named txtAge Variable/Constant/Procedure Names (top) The naming convention of variables/constants/procedures is not vital, but is If you have declared a variable then VB will automatically convert all instances For example if you are unsure if the variable boxColour
This is my first tutorial to PSC, so please be kind with any comments...
a few simple basic tips that will help you in your coding. These are all useful
tips that will speed up your programming and, as your programs get larger, your
debugging.
along the lines of:
Dim a, b, c, d
a = Text12.Text
b = Text3.Text
If a = b Then
...
Code represents code examples.
Text represents a comment.
Note: Explains some of the code in the examples.
Procedure: a Sub or function.
2. Code Formatting
3. Commenting
4. Variable Types
5. Static Variables
6. Global/Local Variables
7. Public/Private Functions
8. Arrays
9. Constants
10. Control Names
11. Variable/Constant/Procedure Names
that does not exist VB will stop executing the code and inform you of this.
If you do not include Option Explicit and misname a variable then VB will assume
create a new variable with a value of 0 or null. For example:
myName = "BOB"
If myyName = "" Then
MsgBox
"Hello " & myName
End If
IF statement is reached. If Option Explicit is
not used the code will not display a message, as VB will assume myyName
is different from myName. It will create the variable
myyName (of type Variant) with an initial value of
"", because of this the message box will
not be displayed.
of lines are used a small mistake can stop the entire code from working.
line of code for a form or module, before any declarations or procedures.
of the code. This is the first thing another programmer will see when they open
your program, and they will be more likely to peruse and attempt to understand
your code if it appears friendlier. Formatting is easy to remember:
MsgBox
"(c) me, 2002"
End Sub
or DO loop the code should be indented an additional
tab.
Dim
i as Integer
For
i = 1 to 10
txtResults.Text
= txtResults.Text & i & vbTab & i^2 & vbCrLf
Next
i
MsgBox
"(c) me, 2002"
End Sub
Dim i as integer
For i = 1 to 10
txtResults.text = txtResults.text & i & vbTab & i^2 & vbCrLf
Next i
MsgBox "(c) me, 2002"
End Sub
to the text, vbCrLf adds a Carriage Return and Line
Feed characters, which together make the text go to a new line. These are both
VB constants, explained below. i^2 is simply a mathematical
function, representing i x i,
^ represents the mathematical function power. Therefore
i^3 means i x i x i.
in a similar way. The number of spaces per tab can be set in the program options.
as a command. A comment is indicated by a single quotation mark before the text.
The comment can appear on the same line as code but anything after the quotation
will be considered a comment
in indicating to other programmers unfamiliar with your code what each piece
of code does.
project name and the date at the top of the first from/module this makes it
easier for other users to contact you if they wish to use your code. You also
may wish to add a short description of your program. e.g.
'Program: Date Finder
'Author: I. Rule <rulei@fictitional.com>
'Date: 1/1/2002
'
'This program will accept a date and check
'whether it is a leap year.
'****************************************
leap = (year Mod 4 = 0) 'Is this a
leap year?
line of code, to save yourself continually scrolling to see the comments.
'Is this a leap year?
leap = (year Mod 4 = 0)
and if unnecessary, will slow you down. For example:
year = Val(cmdYear.Text) 'Get
the year from the text box
leap = (year Mod 4 = 0) 'Is
this a leap year?
MsgBox leap 'Display
a message box indicating whether this is a leap year.
you the numerical value text, this is useful incase the user types a letter
instead of a number, which would cause the program to crash, instead Val(text)
will return 0. The Mod operator gives the remainder,
so 5 Mod 2 would give 1(the remainder of 5 divided
by 2). The formatting of leap = (year Mod 4 = 0) is
an easy way to get a True/False value. year
Mod 4 gives a number, if this number is 0 then (year
Mod 4 = 0) gives True, if not it gives False.
Therefore leap receives its correct value. The brackets are not necessary but
make the code easier to understand.
it is for your own or others benefit.
Type
Description
Example
Date
Stores a date/time combination
1:46:32 AM 17-02-2002
String
Stores a "string" of text without formatting
Hello Bob
Integer
A non decimal number -32768 to +32768
199
Byte
An integer from 0 to 255, inclusive
16
Long
An integer extending to billions
1132434
Double
Stores decimal and large numbers
1.0002
Single
Stores large numbers
Boolean
A single bit, stores True or False
True
Variant
A variant should not be used, it can store values of any of the above
types, but is very memory intensive and is bad programming practice to use
them.
more advanced you will need to use Long, Double and Date
this.
as Integer
Variant type. Only var3 will be a Boolean type.
the variable will retain its value. For example:
Static
count as integer
count = count + 1
MsgBox
count
End Sub
display "1" the second time it would display "2" and so
on. If Dim were used:
Dim
count as integer
count
= count + 1
MsgBox
count
End Sub
pressing the button would only ever display 1. Static variables are rarely required
and in most cases a global variable is easier to use and more suitable.
defined within a procedure and can only be accessed from within that procedure.
A global variable is defined outside a procedure at the top of the page of code
for that form or module. It can be accessed by all procedures in that module/form,
and will obviously not lose its value once a procedure has finished executing.
e.g.
variable - can be used by any procedure of frmMain
Dim myAge as Integer 'Global
variable - can be used by any procedure of frmMain
Public peopleCount as Integer 'Public
global variable - notice it can be used by modChecks
Dim valid as Boolean 'A
local variable - it can only be used in this sub
valid
= chkValid.Value
If
valid = true Then
myName
= txtName.Text
myAge
= txtAge.text
peopleCount
= Val(txtCount.text)
message
= txtMessage.text
End
If
End Sub
MsgBox
"Name " & myName
MsgBox
"Age " & myAge
End Sub
global variable - notice it can be used by frmMain
If
frmMain.peoplCount > 5 Then
MsgBox
message
End
If
End Sub
This applies when a form or module gets the value of a variable belonging to
another form. If the variable belongs to a module then the form or module can
directly refer to it directly, as is the case for the variable message. These
variables are used as an example - it is up to you to decide whether the variable
is declared in the module or form.
used within their own form or module. Public ones can be used by any form or
module, but if they belong to a form the forms name must be written before the
procedure name.
be placed in the module, if not it is best placed in the form it is used in.
a list. The can be declared as follows:
1. All arrays must be global (i.e. not declared within a procedure).
2. An array that is declared in a form cannot be Public.
you decide on a length after some code has been executed. A ReDim statement
can be called more than once for any array, however each time the values for
each position in the array will be lost.
Private Sub cmdSetLength_Click()
Dim people as integer
people = Val(txtPeopleCount.Text)
ReDim userName(1 To people)
End Sub
as many dimensions as you like (although three is probably the maximum you will
need). Note that if you create an array with many dimensions you may fun out
of memory, as a 8 dimensional array like so userName(1 To
10, 1 To 10, 1 to 10 ...) as String is equivalent to 100,000,000 variables.
ReDim
userName(1 To 10, 1 To 10)
End Sub
creating a variable. Constants cannot be changed at run-time. Typical use may
be:
module using the syntax:
vb. Previously vbTab and vbCrLf were discussed. The most commonly used are for
the basic colours and for key ASCII values (used in the KeyDown and KeyPress
procedures). For a full list check your help file.
Example
Value
vbKeyEscape
27
vbKeyRight
39
vbBlue
16711680
control is placed on the form not after the entire layout is designed. The prefix
for each control should be standard and suggest what type of control it is.
The generally accepted prefixes for the most common controls are:
Control
Prefix
Command Button
cmd
If a label is not used for input or output it is acceptable to leave
its default name.
lbl
Text Box
txt
Form
frm
Picture Box
pic
Image
img
Timer
tmr
Menu
mnu
Check Box
chk
Option Button
opt
etc.
is far more descriptive that one named age, which could be a button, textbox
or even a label. It also means that you don't run into trouble when you want
(for example) a button and textbox to have the same name. Controls can also
exist in arrays - if you copy and paste a control it will ask you if you would
like to create an array. This functionality is rarely needed, but if it is the
Index property represents its position in the array. Controls can only exist
is one-dimensional arrays.
good programming practice and is extremely helpful to someone examining your
code. There is one rule for each type:
Type
Rule
Example
Variables
The name has correct cases except for the first letter, which
is always lower case.
myName
Constants
The entire name is uppercase.
DAYSPERYEAR or DAYS_PER_YEAR
Procedures
All letters are correct cases.
CalculateAverage
of it in your code to the case you used when you declared it. This can be used
if you are unsure what the name of the variable was, if you type is deliberately
in the wrong case and it is correct the case will be changed to mach that of
the declaration.
was spelt boxColour or boxColor
then type: BOXCOLOR and press space/enter, because
there is no variable by this name the case will remain unchanged. Therefore
if you retype the text as to BOXCOLOUR the case will
automatically change to boxColour.
About this post
Posted: 2002-06-01
By: ArchiveBot
Viewed: 104 times
Categories
Attachments
Beginners_547972122002.zip
Posted: 9/3/2020 3:45:00 PM
Size: 8,505 bytes
Loading Comments ...
Comments
No comments have been added for this post.
You must be logged in to make a comment.