- DragDrop Technique
- MouseDown
- SourceControl.Drag in MouseDowm event
- DragIcon of the SourceControl you'are dragging. Pick
DragIcon from available Graphics\Icons\DragDrop subdirectory
- DragOver ' Use this event to give some feedback to
user. Eg: change colour of control when something is dragged over it.
- DragDrop ' Refer to SourceControl to know which control
has just been dropped. Can use property Tag of SourceControl to know more about it. Use
TypeOf function to know what type of SourceControl it was.
-
- VB Programming Syntax
- Naming Convention: txtTextBox, lblLabel,
CmdCommandButton, etcẨ
- Comment character is '
- Variable Declaration: You don't have to declare that
you are about to use a new variable or the data type of that variable.
- Option Explicit ' Always use this statement in the
General Declaration section to indicate that any variables used must be declared first
with a Dim or Global statement. Note that variables are initialised to 0 for
number and Null string for string.
- Program Statement can be single statement or Block of
statements.
- What is a Block of statements?
- Assignment concept:
- The statement
- Counter = Counter + 1
- means getting the Counter value from its storage, adding 1 to
this value,
- then put it back to Counter storage. The = sign does not mean
EQUAL
- Arithmetic Expression
- Like algebra, Multiplication and Division take precedence over
Addition and Substraction. If in doubt, use single brackets.
- Arithmetic Operators: +, -, *, / , Mod, \
- Logical Expression is used in If ..Then..Else.. End If
statements. The result is True or False, and cannot be used for arithmetic calculation.
- NOT, AND take precedence over OR. If not sure use single
brackets. Eg:
- If ItsHot OR theSunShines AND IamFree Then
- IgotoTheBeach
- End If
- Is the same as
-
- If ItsHot OR (theSunShines AND IamFree) Then
- IgotoTheBeach
- End If
Logical operators: >, < ,=, <=, >= , <>,
NOT
-
- Data Types
-
- Integer ' -32,768 to 32,767; fractions are rounded.
- Single ' floating point number stored in 4 bytes
- Boolean ' Store True or False
- String ' Such as "Hello, world!"
- A character is a string of one character.
- Variant ' General purpose data type
- Date ' Store Date
- Array of Variables
- Array of Controls, Index
-
- Scope (or
Visibility) of Variables
-
- Global ' Declare Globally in Module
- Dim ' Declare locally, with or without data type
- Public ' let people access
- Private ' only use inside this Form/Module
- Static ' Variable value retains even after the Sub/Function
had reached the end.
-
- In general:
- Variables declared within a Sub/Function disappears once the
execution reaches the end.
- No Sub/Function can access variables declared locally inside
another Sub/Function
- Anything from one Form cannot access variables in another
Form.
- All Subs, Functions of a Form/Module can access its General
Declaration Section
- All Subs, Functions of a Project can access everything
declared Public and Global in the Modules
-
- Sub and Function
-
- Parameters act as place holder. They can have different names
from variables passed to the Sub/Function.
- Parameters may be damaged by Sub/Function process. To avoid
damage use ByVal
- The following example uses the Sub statement to define the
name, arguments, and code that form the body of a Sub procedure.
- ' Sub procedure with two arguments.
-
- Sub ComputeArea (Length, TheWidth)
- Dim Area As Single ' Declare local variable.
-
- If (Length = 0) Or (TheWidth = 0) Then
-
- ' If either argument = 0.
-
- Exit Sub ' Exit Sub immediately.
- End If
- Area = Length * TheWidth ' Calculate area of rectangle.
- Debug.Print Area ' Print Area to Debug window.
- End Sub
- Function Returns a Value in the declared Data Type.
- Eg: Function IsDate (MyDate.text) returns a Boolean value (ie.
True/False) after checking if MyDate.Text is a valid date.
- Function UCase(myString) returns a String which is myString
converted to Uppercase.
- Side Effects means Paramaters passed to Function being damaged
by the Function process without user's knowledge.
- This example uses the Function statement to declare the name,
arguments, and code that form the body of a Function procedure.
-
- The following user-defined function returns the square root of
the argument passed to it.
- Function CalculateSquareRoot(NumberArg As Single) As Single
- If NumberArg < 0 Then ' Evaluate argument.
- CalculateSquareRoot = 0
- Else
- CalculateSquareRoot = Sqr(NumberArg) ' Return square
root.
- End If
- End Function
- Some Event Subs are treated just like normal Sub.
-
- Input/Output
text string from/to a text file
Open "todo.txt" for Input as #1 ' Open the Text
file for Input
Do While Not EOF(1) ' Keep reading 1 line at a time until
reaching the end
- Line Input #1, Aline
- List1.AddItem Aline ' Add the line of text to Listbox List1
Loop
Close #1 ' Close the file
Open "todo.txt" for Output as #2 ' Open the Text
file for output
' Output content of Listbox List1 to "todo.txt"
For i = 0 to List1.Listcount-1 ' Go thru from 1st
to last line in List1
Print #2, Aline ' Write the line of text to file
Next i
Close #2 ' Close the file
- The App object
-
- App.Path ' Return the Folder where Application file
(ie. .exe ) resides
- It may not be terminated with "\" so to make sure
append the character "\" on the right if the last character is not
"\":
LocalDir = App.Path
If Right(LocalDir,1) <> "\" then
LocalDir = LocalDir & "\"
End if
-
- App.PrevInstance ' Use this to check if the program has
already been loaded. ie. We don't want user to load several copy of the programs.
- If App.PrevInstance = True then
- MsgBox "This program is active, please restore its
window and use."
- End ‘ Terminate the program
- End if
-
-
- Use the menu command Project | Properties (click Tab MAKE) to
enter the Major and Minor Version number of your application and to select the icon of
which form as the icon of the application.
-
- Data type functions
-
- IsNumeric checks if the string represents a number
- IsDate checks if the string represents a valid Date
- Example:
- If IsDate(theDate.text) Then
- TheDate.text = Format(theDate.text, "dd/mm/yyyy")
- End if
- Val , CSng convert a string to a number.
- Str converts a number to a string, watch that it gives
you a blank space on the left of the number string
-
- Sendkeys Function
-
- Sendkeys "Very Good" ' Emulate entering the
"Very Good" keystrokes
- Sendkeys "{TAB}" ' Emulate tapping the TAB key
- "+bc" ' SHIFT "bc", hold down the Shift
key while pressing b and c
- "^m" ' CTRL m, hold down the Ctrl key while pressing
m
- "%h" ' ALT h, hold down the Alt key while pressing h
-
- Control Flow
-
- Flow of execution of code may be changed with Control Flow
facilities
- Selection with If and Case
statements
-
- If WeeklyIncome < 100 then
- Tax = 0.0
End If
If OutsideTemparature >= 35 then
GotoTheBeach
Else
GotoTheMovies
End If
If Age > 60 then
Category = Pensioner
ElseIf Age < 18 then
Category = Child
Else
Category= Adult
End if
- Select Case GivenNumber ' Evaluate GivenNumber.
- Case 1 To 5 ' Number between 1 and 5.
- Debug.Print "Between 1 and 5"
- ' The following is the only Case clause that evaluates to
True.
- Case 6, 7, 8 ' Number between 6 and 8.
- Debug.Print "Between 6 and 8"
- Case Is > 8 And GivenNumber < 11 ' Number is 9 or
10.
- Debug.Print "Greater than 8"
- Case Else ' Other values.
- Debug.Print "Not between 1 and 10"
- End Select
-
- Iteration with For and Do
statements with For and Do
statements
- Use For..Next when there is a fixed number of
iterations
- The following example uses the For...Next statement to
create a string that contains 10 instances of the numbers 0 through 9, each string
separated from the other by a single space. The outer loop uses a loop counter variable
that is decremented each time through the loop.
Dim i, Chars, MyString
MyString=""
- For i = 10 To 1 Step -1
' Set up 10 repetitions.
- For Chars = 0 To 9 ' Set
up 10 repetitions.
- MyString = MyString & Chars '
Append number to string.
Next Chars ' Increment counter
MyString = MyString & " "
' Append a space.
- Next i
- Use Do.. Loop when you are not sure of the exact number
of iterations.
- The following example shows how Do...Loop statements
can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to
False, and exits prematurely using the Exit Do statement. The outer loop exits immediately
upon checking the value of the flag.
-
- Dim Check, Counter
- Check = True: Counter = 0 ' Initialize variables.
- Do ' Outer loop.
- Do While Counter < 20 ' Inner loop.
- Counter = Counter + 1 ' Increment Counter.
- If Counter = 10 Then ' If condition is True.
- Check = False ' Set value of flag to False.
- Exit Do ' Exit inner loop.
- End If
- Loop
- Loop Until Check = False ' Exit outer loop immediately.
-
- Note that a
- Do While (Logical Expression)Ẩ
- Ẩ..
- Loop
- may not go through the loop at all if the condition is not
satisfied at the beginning.
- Whereas
- Do
- Ẩ.
- Loop Until (Logical Expression)
- will go thru the loop at least once, because the Logical
Expression is not calculated until the end of the loop.
- When you use a Do Loop remember to initialise some data value,
such as i.
- Goto Label ' Label must be terminated with a colon eg:
DoAgain:
-
- String manipulation
-
- MyString = "" ' assign a null string to MyString,
ie. Clear the string
- String concatenation symbol &
Example: ResultString = "Hello, " &
"World! " & " How are you?"
ResultString = Left (GivenString, 4) ' Extract leftmost 4
characters
ResultString = Right(GivenString, 6) ' Extract rightmost 4
characters
ResultString = Mid(GivenString, 5,8) ' Extract rightmost 8
characters, starting from column 5
ResultString = Mid(GivenString, 12) ' Extract the remaining
of the string starting from Column 12
ResultString = Space(40) ' Return 40 blank spaces
Pos= InStr(GivenString,"Hello") ' Return column
where substring "Hello" is found.
GivenString = Trim(GivenString) ' Remove both leading and
trailing blank spaces
ResultString = Ucase(GivenString) ' Convert all characters in
given string to Uppercase
- Example: Obtain Firstname, Middlename and Surname
from the full name
-
- Date manipulation
- Now ' Return current Date and Time
- TheShortDate = Format (Now, "dd/mm/yy")
- Be wary of Year2000 compliance
- DateDiff ("d", Now, AfutureDate)
- TwoHourLater = DateAdd("h",2, Now )
- MyDate = #February 12, 1969# ' Assign a date.
- MyWeekDay = Weekday(MyDate) ' MyWeekDay contains 4 because
- ' MyDate represents a Wednesday.
- Example: Obtain current Date in format like "Saturday,
21 February 1998"
-
- Debugging facilities
- Place the cursor on top of a variable to see its value.
- Toggle BreakPoint with F9 or by clicking on the left
margin of source code.
- Step Over a Sub/Function with Shift+F8
- Drag Round dot on the left margin to required Next
Statement
- Add Watch
- When value changes
- When value is TRUE, where value can be an expression.
-
- Immediate Window
- Use Print statement to examine data. Press enter on any
statement to execute it.
- Can insert temporary statement to change value of variables
- Terminate the program by using the Menu command Run | End or
by clicking the square symbol.
|