VB6 Notes - leobs.net

advertisement
Control Prefixes
Dim MyName As ListOfNames
cbo
cdl
chk
clm
cmd
col
ctl
dir
drv
dta
fil
fra
frm
grd
hsb
img
iml
lbl
lin
lst
mnu
mod
obj
ole
opt
pic
res
shp
sld
tlb
tmr
txt
vsb
Private Sub Form_Load ()
MyName.Name = "Leo Bramwell-Speer"
End Sub
Combo box
Common dialog control
Check box
Class module
Command button
Collection
Control
Directory list box
Drive list box
Data control
File list box
Frame
Form
Grid
Horizontal scroll bar
Image
Image list
Label
Line
List box
Menu
Standard module
Object
OLE client
Option button
Picture box
Resource file
Shape
Slider
Toolbar
Timer
Text box
Vertical scrollbar
Datatypes
Boolean
Byte
Currency (Suffix ‘@’)
Date
String [*6]
Integer
Long (Suffix ‘&’)
Single (Suffix ‘!’)
Double (Suffix ‘#’)
Variant
True (-1)/False (0) (default
false)
0-255
£32.12
dd/mm/yyyy
“xxxxxx”
-32,768 – 32,767
-2,147,483,648-2,147,483,647
-3.4E+38 – 3.4E+38
-1.8E+308 – 1.8E+308
Any datatype
To create own datatype:
Option Explicit
Private Type ListOfNames ‘(Public by default)
Name As String * 20
End Type
Enumeration:
Option Explicit
Private Enum MakeOfCar
Ford
Volvo
End Enum
Dim MyCar As MakeOfCar
Private Sub Form_Load ()
MyCar = Volvo
End Sub
Operators
11/4=2.75
11 Mod 4=3 (remainder)
11\4=2 (integer result)
Message/Input Box Named Literals
Buttons:
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbMsgBoxHelpButton
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
Icons:
vbCritical
vbQuestion
vbExclamation
vbInformation
vbSystemModal (box stays on top no
matter what application you are in)
Return Values:
Message Box (can use Dim M As VbMsgBoxResult)
vbOK
1
vbCancel
2
vbAbort
3
vbRetry
4
vbIgnore
5
vbYes
6
vbNo
7
Input Box
‘Cancel’
Null string
Other Named Literals
Colours
vbBlack, vbRed, vbGreen, vbYellow, vbBlue,
vbMagenta, vbCyan, vbWhite (can also use &HFF00FF)
in hex
KeyCode
vbKey A etc, vbKey7 etc, vbKeyF1 etc, vbKeyNumpad0
etc, vkKeyBack, vbKeyTab, vbKeyReturn, vbKeyShift,
vbKeyControl, vbKeyPause, vbKeyCapital,
vbKeyEscape, vbKeySpace, vbKeyPageUp, vbKeyEnd,
vbKeyHome, vbKeyLeft/Up/Right/Down
StartUpPosition 0-Manual (no setting specified), 2CentreScreen, 3-Windows Default
(upper left corner)
Style
0-Standard, 1-Graphical – needed for
pictures and to change BackColor on
buttons
TabIndex
Number showing order of tab cycle
TabStop
“
if false misses object
Visible
True/False
WindowState 0-Normal, 1-Minimized, 2-Maximized
WordWrap
True/False
Functions
Control Properties
Alignment
Appearance
AutoRedraw
BackColor
0-Left Justify, 1-Right Justify, 2-Centre
0-Flat, 1-3D
For persistent bitmap
Background colour of labels, shapes
etc, BackStyle must be set to opaque
BackStyle
0-Transparent, 1-Opaque
BorderColor
Border colour for lines, shapes etc
BorderStyle
0-None, 1-Fixed Single for labels,
0-None, 1-Fixed Single, 2-Sizable for
forms, 1-Solid, 5-Dash-Dot-Dot for
lines/shapes
BorderWidth Width of line, shape
Cancel
If True sub called when Esc pressed
ControlBox
True displays min, max & ‘X’ icons
Default
If True sub called when Return
pressed
DrawMode
13-Copy Pen, 7-Xor Pen etc
DrawStyle
0-Solid, 1-Dash, 5-Transparent etc
DrawWidth
Width of line
Enabled
True/False (objects greyed out, forms
are not)
FillColor
For shapes, colour of interior area
FillStyle
For shapes, 0-Solid, 1-Transparent, 3Vertical Line etc, interior area
FontTransparent
True/False. If True, text
printed on form etc doesn’t delete
background image
Icon
For forms, application icon
MaxButton
For forms. False greys out max button
MinButton
For forms. False greys out min button
MouseIcon
Set custom mouse icon
MousePointer 0-Default, 1-Arrow, 11-Hourglass, 99Custom
Moveable
For forms, if false, can’t move form
(Name)
Object identifier
Picture
For forms etc, background image
Shape
Shape of shape control eg rectangle
ShowInTaskbar Display form in taskbar
Int=MsgBox (“Message”[,vbCritical + etc][,”Title”])
Str=InputBox (“Question?”[,”Title”][,DefaultValue]
[,Xpos][,Ypos])
Abs ()
Absolute value
Sin (), Cos () etc Trig functions
Len ()
Number of bytes eg Len (“123”)=3,
Len (Integer)=2
Exp (), Log () Natural log base, natural log
Chr (Num)
Returns ASCII character
InStr ([Start,]Str1,Str2) Returns start pos of Str2
within Str 1 starting at Start
Join (Str ()[,delimiter]) Merges string eg a(0)=”Leo”,
a(1)=”was”, a(2)=”here” – Print Join
(a,”*”) returns “Leo*was*here” (uses
space if no delimiter)
LCase (Str), UCase (Str) Returns string in
lower/uppercase
Left (Str, Int) Left (“Leo”,2) =”Le”
Right (Str, Int) Right (“Leo”,2)=”eo”
Mid (Str, Start, Len)
Mid (“Leo”,2,1)=”e”
LTrim (Str), RTrim (Str) Trims spaces
Str (Num)
Converts number to string - NOTE Use
LTrim (Str(123)) to remove spaces
Val (Str)
Converts string to number eg
Val(“123”)=123 - NOTE Val
(“Leo123”)=0, Val (“Le123o”)=0, Val
(“123Leo”)=123, Val (“12Leo3”)=12
Date, Time, Now, Timer
Current date,
time, date & time, seconds since midnight
DateSerial (yyyy,mm,dd)
Assigns date to date
datatype eg MyBday=DateSerial (1974,3,31) – NOTE
Can also use MyBday=#3/31/1974# or
MyBday=DateValue (“March 31, 1974”)
TimeSerial (hour, min, sec)
As above for time
NOTE Can also use MyTime=#14:12:24# or
MyTime=TimeValue (“14:12:24”) or both of the above
eg MyBday=#3/31/1974 11:40:00 PM#
DateDiff (Str,Date1,Date2)
Returns number of
time intervals between 2 dates where Str is:
‘h’ Hour, ‘d’ Day, ‘m’ Month, ‘n’ Minute, ‘s’ Second,
‘ww’ Week (eg 13 for MyBday), ‘yyyy’ Year, ‘y’ Day of
year (eg 90 for MyBday), ‘w’ Day of week (eg
1=Sunday)
Eg Print DateDiff (“s”, MyBday, Now) prints number of
seconds since birth
DatePart (Str,Date)
Returns Str (see box above)
portion of date
DateAdd (Str,Num,Date)
Adds Num number of
time units to Date. Time unit specified by Str (box)
WeekdayName (weekday[,abbrev][,1st day of week])
eg WeekdayName (DatePart (“w”, MyBday), True,
vbSunday) returns ‘Sun’
MonthName (month[,abbrev]) Returns name of
month
IsDate ()
True if argument can convert to date
IsEmpty (Var) True if variable has not been
initialized with value since declaration
IsNull ()
As above but for controls as well
IsNumeric ()
True if argument can convert to
numeric datatype
VarType (Var) Returns variable datatype eg Print
VarType (“Leo”) returns 8 (string)
Asc (Str)
st
Converts 1 character of string to
ASCII value
CDbl ()
To equivalent double datatype
CInt ()
Rounds fractional argument down if
<=0.5 or up to integer)
Int ()
Always rounds down
CLng ()
Converts to long datatype
CSng ()
Converts to single datatype
CStr ()
Converts to string datatype
CVar ()
Converts to variant
Fix ()
as Int but Int converts -8.4 to -9. Fix
converts to -8
Round (Num, Number of decimal places) eg Print
Round (0.235, 2) returns ‘0.24’, same as Format
(0.235, “0.00”)
Sgn ()
Returns sign of number (>0 is 1, =0 is
0, <0 is -1)
Hex ()
Converts to hexadecimal
Oct ()
Converts to octal
Format (0.235, “#.00”)=’.24’ (“0.00”=’0.24’)
MyStr=Format (MyTime, “h:m:s”) returns ‘17:2:23’
MyStr=Format (MyTime, “hh:mm:ss AMPM”) returns
’05:04:23 PM’
MyStr=Format (MyBday, “dddd, d mmmm, yyyy”)
returns ‘Sunday, 31 March, 1974’
If a format is not supplied, a string is returned:
MyStr=Format (23) returns “23”
User defined formats:
MyStr=Format (5459.4, “#,##0.00”) returns ‘5,459.40’
MyStr=Format (334.9, “###0.00”) returns ‘334.90’
MyStr=Format (5, “0.00%”) returns ‘500.00%’
MyStr=Format (“HELLO”, “<”) returns ‘hello’
MyStr=Format (“This is it”, “>”) returns ‘THIS IS IT’
Format (expression, strFormat) where a=1234.5678
and b=false boolean:
Format (a,”currency”) returns ‘£1234.5678’
Format (a,”fixed”) returns ‘1234.57’
Format (a, “general number”) returns ‘1234.5678’
Format (a, “percent”) returns ‘123456.78%’
Format (a, “scientific”) returns 1.23E+03
Format (b, “on/off”) returns ‘Off’
Format (b, “true/false”) returns ‘False’
Format (b, “yes/no” returns ‘No’
UBound ()
CurDir ()
FreeFile ()
Returns highest subscript of array
Returns current directory
Returns next available file number
(channel)
Kill (“oxo.exe”) Permanently delete file
Declarations
OPTION EXPLICIT
‘Private’ and ‘Dim’ (its scope is local) are the same.
Convention is to use ‘Private’ at module level and
‘Dim’ at sub/function level.
Public (global scope) in form module:
(In form module 1):
Option Explicit
Public N as String
(In form module 2):
Print Form1.N
Public in standard module:
(In standard module):
Option Explicit
Public N as String
Public Sub Blob
N=”Leo”
End Sub
(In form module):
Blob
Print N
Debugging








View > Toolbars > Debug
Press Alt + Tab to see running window.
Debug > Toggle Breakpoint (or F9 or click grey
area to left of code). Appears as brown circle
and line of code highlighted in brown. Enters
break mode before program line executes.
Yellow arrow indicated where program is at.
Mouseover to see values. Play button to
resume.
Debug > Add Watch – Enter expression eg
N>3 then select watch type eg ‘Break when
value is true’ to trigger breakpoint.
Can drag mouse over variable or expression
then see Quick Watch (Debug > Quick Watch)
to see expression and value. Can then Add
Watch.
Step Into button executes code one line at a
time. Step Over skips procedures. Step Out in
procedure skips rest of procedure and returns
to calling procedure.
The Call Stack window lists all called
procedures.
You can use the Immediate window to either
Print variable or change variable or call it from
code eg Debug.Print N
Objects
System Objects
Sys Object
Methods
App
EXEName
Path
Title
PrevInstance
Clipboard
Debug
Printer
Screen
App’s filename
App’s path
Form’s title
True if another copy
of app is running
Clear
Erase contents of
GetData
Get graphic from
GetFormat
Get format from
GetText
Get text from
SetData
Copy graphic to
SetText
Copy text to
Print
Send to immediate
window
(See printer object)
FontCount
Number of fonts on
system
Fonts(Int)
Font name
MousePointer Type of mouse
cursor
TwipsPerPixelX
Number of
TwipsPerPixelY possible twips
Width/Height Width/height in twips
Object Basics
A Class is a packaged object, with behaviours and
properties that describe members of the class eg an
option button class defines properties, methods and
events that all members of that class support.
You can test for memberships within any given class.
One of the reasons for a class test is that you can pass
controls to procedures eg:
Public Function ErrorCheck (txtInput as TextBox, Min,
Max As Single) As Boolean
If Not ErrorCheck (txtMain, 1,5) Then Beep
Procedures can be multipurpose eg a proc might
change the BackColor property of whatever object you
pass to it by using As Object:
Private Sub ChangeColour (objOnForm As Obect)
Object variables can be defined as object datatypes:
Dim objMyLabel As Object
Then you can reference an existing object with Set:
Set objMyLabel as lblMain
objMyLabel.Caption = “Hello world!”
Use With..End when setting multiple properties:
With objMyLabel
.ForeColor = vbRed
.Caption = “Hello world!”
End With
Object variables can be declared as generic controls:
Dim objMyLabel As Label
Set objMyLabel = lblMain
You can create object variable arrays:
Dim objLabels (1 to 3) As Label
You can test an object’s datatype with the TypeOf..Is
keyword and the TypeName function:
If TypeOf objMyObject Is Label Then Beep
Print TypeName (objMyObject)
New Keyword
Use the New keyword to create a new object as
defined by its class. To create a new form:
Private Sub Command1_Click ()
Dim x As Form
Set x = New frmMain
x.Show
End Sub
Collections
A Collection is a set of all objects of the same
datatype. The Controls Collection refers to every
control in the application. The Forms Collection refers
to every form. Eg you have 3 labels on a form:
For n = 0 To Controls.Count – 1
Controls (n).Caption = “Hi!”
Next
Note zero-based collection subscript even though
Controls.Count=3.
Before is a named argument (an argument known by
its name and not by its position within an object list.
‘:=’ is its named argument assignment operator.
You can use For Each but you must declare a control
variable so that it has a place to load each control in
the collection:
Dim ctlMyControl As Control
For Each ctlMyControl In Controls
ctlMyControl.Caption = “Hi!”
Next
Private Sub clmMain_Click ()
Set clsNew = New clmShowMe
clsNew.ShowFrm ()
End Sub
Methods you can apply to collections:
Add
Add item to collection
Count
Number of items
Remove
Delete item
Item
References collection element
Class Modules
The New keyword can be used to create collections
and objects from the classes you define in Class
Modules. Eg to create a new instance of the class
clmShowMe and call the procedure contained in the
class module:
And in the class module:
Sub ShowFrm ()
Dim frmNew As Form
Set frmNew = New frmMain
frmNew.Show
frmNew.WindowState = 1
End Sub
OLE Automation
To declare your own collection:
Dim colNewCollect As New Collection
Or in general section:
Public colNewCollect As New Collection (project
level)
Private colNewCollect As New Collection (module
level)
Code:
Option Explicit
Dim n As Integer
Dim colPeople As New Collection
Private Sub Form_Activate ()
colPeople.Add “George”
colPeople.Add “Sandra”
colPeople.Add “William”
Display (3, George, Sandra, William)
colPeople.Add “Fred”, before:=1
Display (4, Fred, George, Sandra, William)
colPeople.Remove 2
Display (3, Fred, Sandra, William)
End Sub
Private Sub Display ()
Print colPeople.Count
For n = 1 To colPeople.Count
Print colPeople (n)
Next
End Sub
This is the capability of one application to declare and
use ActiveX objects that are created by other
applications ie you can control an application such as
Word or Excel. All their internal properties, events and
methods are exposed. Eg VB will borrow Word
(without ever showing it) and make it create a file for
you. When finished, no traces of Word will be left and
the user will think your application created the file.
Code:
Option Explicit
Public objWordApp As Object ‘Public as var
references a completely different application outside
this app’s workspace.
Private Sub Form_Load ()
Set objWordApp = GetObject (“”,
“Word.Application.8”) ‘Get Word if it’s currently
running. The null string creates a new document. If
you want to open an existing Word document and
work on that document inside VB, insert path &
filename on that doc into string.
If objWordApp Is Nothing Then Set objWordApp =
CreateObject (“Word.Application.8”) ‘If no instances
of Word running then create one. CreateObject starts
Word in background. Set tells VB to reference Word.
objWordApp works like a link to Word. VB will transfer
functions you apply to objWordApp to Word.
objWordApp.Documents.Add ‘Add document to
collection.
objWordApp.Documents (1).Content.Font.Bold =
True
objWordApp.Documents (1).Content.Font.Size = 18
objWordApp.Documents (1).Content.InsertAfterText
= “My document!” & vbCrLf & vbCrLf ‘vbCrLf is
named literal simulating using pressing enter.
objWordApp.Documents (1).Range.InsterAfterText =
“How do you like it?” ‘Range refers to cursor’s current
position in the document.
objWordApp.Documents (1).SaveAs “c:\MyDoc.doc”
‘Save document.
objWordApp.Documents (1).Close ‘Close document.
objWordApp.Documents (1).Quit ‘Exit Word.
Set objWordApp = Nothing ‘Release reference.
End Sub
Loops
For…[Exit For]…Next
Do [{While | Until} condition] ‘Can skip loop.
:
[Exit Do]
:
Loop
Or:
Do ‘Always does at least one loop.
:
[Exit Do]
:
Loop [{While | Until} condition]
Branching
If…Then…Else [If]…End If
Select Case Age
Case 0: …
Case Is < 5: …
Case 5 To 10: …
Case Else: …
End Select
Subroutine and Function Procedures
Subroutine
Private Sub Xyzzy (var As Single)
:
End Sub
Call with Xyzzy or Call Xyzzy.
Function (returns value)
lblMain.Caption = Area (txtInput.Text)
Private Function Area (a As Single) As Single ‘Second
As Single is datatype of return value (Area).
Area = 2 * Pi * a
End Funtion
Static preserves local variables between calls eg:
Private Static Sub cmdMain_Click ()
Dim z As Single
z=z+1
Print z
End Sub
Can also use Static z As Single instead.
Use ByVal to retain calling procedure’s variables eg:
Option Explicit
Dim a As Integer
Private Sub Form_Load ()
a=5
End Sub
Private Sub cmdMain_Click ()
Print Func (a); a
End Sub
Private Function Func (ByVal a As Integer) As Integer
a=a+1
Func = a
End Function
Return ‘6 5’ each time (otherwise would return ‘6 6’,
‘7 7’, ‘8 8’…
Use just parentheses when calling procedure’s
argument contains array eg:
Private Function Maze (x (), y () As Single) As Single
Labels
Caption
WordWrap
BackStyle
“Hello world!” &…
True/False
0-Transparent, 1-Opaque
Command Buttons
Private Sub cmdCommand1_Click ()
cmdCommand1.Enabled = True/False
Can load picture but need to set Style to 1-Graphical.
List Boxes
Methods
lstMain.AddItem (“Henry”) ‘At Form_Load.
lstMain.RemoveItem (0)
lstMain.Clear
lstMain.ListCount ‘No of items in list.
lstMain.ListIndex = 5 ‘Sets index (selected item).
lstMain.List (0) = “George” ‘Sets 1st item.
Properties
Columns
Number of columns
IntegralHeight True/False: Displays partial items if
false
MultiSelect
0-None: Select only 1 item at a time
1-Simple: Select multiple items
2-Extended: Select multiple items by
dragging mouse
Sorted
True/False: Alphabetically sort
Style
0-Standard, 1-Checkbox
Selected
True/False eg If lstMain.Selected (1) =
True Then Beep
Combo Boxes
Style
0-Dropdown Combo: Single line unless
user clicks, can add items
1-Simple Combo: Multiple lines, can
add items
2-Dropdown List: Single line unless
user clicks, cannot add items
To act on a selected item:
Private Sub cboMain_Click ()
If cboMain.ListIndex = 1 Then Beep
[Or]
If cboMain.Text = “Leo” Then Beep
End Sub
To add an item:
Private Sub cboMain_KeyDown (KeyCode As Integer,
Shift As Integer)
If KeyCode = vbKeyReturn And cboMain.Text
<> “” Then cboMain.AddItem cboMain.Text
End Sub
Option Buttons & Check Boxes
Put in a frame to make a set. Place frame on form 1st.
Appearance
0-Flat, 1-3D
Style
0-Standard, 1-Graphical
Value (buttons) True/False
(boxes) 0-Unchecked, 1-Checked, 2-Grayed
TabIndex
0,1,2…: Move focus with tab
TabStop
True/False, skipped if false
Alignment
0-Left Justify, 1-Right Justify: Places
caption to left or right of button/box
Timer & Scroll Bars
Timer
Interval
Between 1 & 65535 milliseconds
Scroll Bar
Max & Min
LargeChange
SmallChange
Value
Between 0 & 32767
Change amount when click on shaft
Change amount when click on arrows
Value
Can use both Private Sub vsbScroll1_Scroll for when
dragging thumb in real time, or Private Sub
vsbScroll1_Change.
Text Boxes
Text
Locked
MaxLength
“Hello!”
True/False: Can’t edit text if false
Maximum number of characters
allowed
MultiLine
True/False. If true can accept
multiple lines of text (best to then set
property ScrollBars to 2-Vertical)
PasswordChar eg ‘*’, everything typed will appear as
stars
Private Sub txtInput_KeyDown (KeyCode As Integer,
Shift As Integer)
If KeyCode = vbKeyReturn Then x = Val
(txtInput.Text)
End Sub
Data Control
Caption
Caption
DatabaseName Excel file
RecordSource Database table
Then use label (or text box to amend). Properties:
DataSource
Data control
DataField
Database field
OLE Control
Can insert either eg blank Word document (Create
New) or file (Create From File). Leave Link checkbox
unticked to embed file in your application or tick it to
link (contain pointer to object, so if object changes
this will be reflected in your application; the object
isn’t stored in your application but the link to the
object is). Can use this code to open item:
oleText.SourceItem = cldOpen.FileName
oleText.CreateLink (cdlOpen.FileName)
oleText.DoVerb
Printer Object
Properties
Copies, DeviceName (name of printer), DriverName,
Font, FontBold, FontItalic, FontUnderline, FontCount
(printer’s number of installed fonts), FontName, Fonts
(table of values stored as if in control array – Fonts (0)
to Fonts (FontCount – 1) holds name of all installed
fonts), FontSize, FontColor, Orientation (1-Portrait, 2Landscape), PrintQuality (1-Draft, 2-Low, 3-Medium,
4-High), Zoom (negative number to make smaller),
Width/Height (in twips).
Methods
Circle, Line, EndDoc (releases doc to printer spooler),
KillDoc (terminates current print job), NewPage (page
break), PaintPicture (send graphic image file to
printer), Print, PSet, CurrentX, CurrentY, TextWidth,
TextHeight (“Leo”)
Eg:
a = “Hello world!”
Printer.FontBold = True
Printer.FontItalic = True
Printer.FontSize = 12
Printer.ForeColor = vbMagenta
Printer.PSet ((Printer.Width – Printer.TextWidth (a))
/ 2, PrinterHeight / 2)
Printer.Print a
Printer.EndDoc
Hint: Send user message box ‘Make sure printer is
ready’, vbCritical, vbOKCancel, before printing.
Hint: Find number of lines that fit on one page with
Printer.Height / Printer.TextHeight (“X”)
Picture Box & Image Controls
Picture Box
AutoSize
True/False: Adjust picture box borders
to fit picture
FontTransparent True/False
Align
Aligns within form, but eg if left
aligned would increase size of box to
top/bottom edges of form. Useful for
eg menu buttons on top of form
Image Control
Stretch
True/False: Stretch to fit borders
Visible
True/False
imgMain.Picture = LoadPicture (“c:\Dinosaur.jpg”)
‘Use “” to clear image.
Hint: Use picture box when animating to avoid flicker.
Make sure you’re using pixel ScaleMode and don’t
forget to DoEvents (can be quicker) or Refresh if in
loop.
Hint: Make picture box transparent by setting
Appearance to 3D and BorderStyle to none.
Hint: Only image controls can be stretched. They
consume less resources and are more efficient.
Toolbars
Add component ‘Microsoft Windows Common
Controls 6.0’. Add ImageList control. In properties
click ‘(Custom)…’ > Images tab > Insert Picture. Add
icons.
Add Toolbar control. In properties click ‘(Custom)…’,
select image list from ImageList dropdown. Can also
change Appearance, BorderStyle & Style (0tbrStandard, each button has border; 1-tbrFlat, only
when you mouseover).
Buttons tab > Insert Button. Change Image: value to
image’s Index: property value. Put ‘Open’ etc in Key:
value, Put ‘Open File’ etc in ToolTipText. Code:
Private Sub tlbMain_ButtonClick (ByVal Button As
MSComctlLib.Button)
Select Case Button.Key
Case Is = “Open”
Call tlbOpen ‘Or mnu if have
menu bar.
:
End Select
End Sub
Common Dialog Controls
Open/Save As, Color, Font, Print, Help
Project > Components > Microsoft Common Dialog
Controls 6.0 (can add other ActiveX controls with .ocx
filename extension).
Properties > (Custom)… to set properties at design
time.
Load/Save Dialog
Private Sub Form_Load ()
cdlLoad.DialogTitle = “Open”
cdlLoad.InitDir = “c:\Windows\Desktop”
cdlLoad.Filter = “Pictures
(*.bmp;*.ico)|*.bmp;*.ico”
cdlSave.DialogTitle = “Save”
cdlSave.InitDir = “c:\Windows\Desktop”
cdlSave.Filter = “Bitmap (*.bmp)|*.bmp”
End Sub
Private Sub cmdLoad_Click ()
cdlLoad.ShowOpen
Set pctMain.Picture = LoadPicture
(cdlLoad.FileName)
End Sub
Private Sub cmdSave_Click ()
cdlSave.ShowSave
SavePicture pctMain.Image,
cdlSave.FileName
End Sub
Another example…
Private Sub Form_Load ()
cdlOpen.DialogTitle = “Open”
cdlOpen.Filter = “Text Documents
(*.txt)|*.txt|All Files (*.*)|*.*”
cdlOpen.FileName = “*.txt”
End Sub
‘ Common dialog property CancelError has to be true.
Private Sub cmdLoadText_Click ()
On Error GoTo ErrHandler ‘Cancel button
clicked.
cdlOpen.ShowOpen
:
Exit Sub
ErrHandler:
:
Exit Sub
End Sub ‘Note only 1 End Sub allowed.
Colour Select Dialog
cdlColour.DialogTitle = “Select Colour”
cdlColour.ShowColor
lblMain.BackColor = cdlColour. Color
Printer Dialog
cldPrinter.DialogTitle = “Print”
ScaleWidth/ScaleHeight Internal measurement
ScaleTop/ScaleLeft
using ScaleMode eg 1-Twip,
3-Pixel.
txtInput.SetFocus
pctMain.Cls
Bool = Not Bool to flip-flop a boolean.
cdlPrinter.ShowPrinter
Font Dialog
cdlFont.DialogTitle = “Font”
cdlFont.FontName = “Arial”
cdlFont.Flags = cdlCFEffects Or cdlCFBoth ‘Enables
strikethrough/underline/colour & both printer and
screen fonts.
cdlFont.ShowFont
Misc
Option Base 1 in general section makes data arrays
(subscript in brackets) start at 1 instead of 0 (or you
can eg Dim (2 To 5).
Add-Ins > Add-In Manager to load eg Package and
Deployment Wizard or Resource Editor.
Use integer = (Rnd * 2) + 1 or single = Int (Rnd * 3) + 1
to generate random number between 1 and 3.
Methods are not properties or events, they are
routines a control knows how to execute eg
frmMain.SetFocus
Resource Files are very useful (Add-In them), then click
on green cube. Can add bitmap etc then
imgMain.Picture = LoadResPicture (“resPic1”,0). 0Bitmap, 1-Icon, 2-Cursor.
int = Shell ("notepad " & App.Path & "\readme.txt",
vbNormalFocus)
frmMain.DrawWidth = 3
frmMain.DrawMode = vbXorPen
frmMain.FillStyle = vbFSTransparent
MSVBVM60.dll – Runtime.
Use CTRL key to create/select multiple objects. Can
change multiple properties at once.
Can use Format > Make Same Size > Both & Format >
Horizontal/Vertical Spacing & Format > Center in Form
to tidy up objects.
To create Control Array: Create new object with same
name as original object. Then have eg cmdButton (0),
cmdButton (1) etc. Can then use index eg Private Sub
CmdButton_Click (Index As Integer).
KeyPreview = True at Form Load: Sets keyboard
events for forms to be invoked before keyboard
events for controls.
DoEvents
[Call] Form_Activate
Exit Sub or Exit Function
Refresh
Unload Me for multiple forms.
Can use ‘?’ instead of Print.
Top/Left/Width/Height Measurement in twips
including borders and
title bar.
Line [(0,0)] – [Step ‘To make relative] (100,100)[,RGB
(255,255,255)][,BF ‘B=Box, BF=Box fill]
PSet (100,100)
If Hex (Point (x,y) = “FFFFFF” Then Die
pctShip.Top (or Left) = y – 11 ‘Sets the distance
beween the internal top/left edge of an object and
top/left edge of its container.
Private Sub Form_MouseDown (Button As Integer,
Shift As Integer, X As Single, Y As Single)
If Button = 1 (1-Left, 2-Right mouse button)
Then Line - (X,Y)
Private Sub Form_KeyDown (KeyCode As Integer,
Shift As Integer)
If KeyCode = vbKeyEscape Then End ‘Use
KeyPress for ASCII codes.
Print “Leo”, ”Leo”
Print “Leo” & (or ;) “Leo”
Print Spc (10); ”Leo”
Print Tab (2); “Leo”
Print TextWidth ("Leo")
Print Chr (13)
Print Chr (10)
Print Chr (34)
Leo
Leo
LeoLeo
Leo
[2nd tab across] Leo
18 (pixels etc)
[Carriage return]
[Line feed]
[Embedded quotes]
Useful Code
Passing text box input to form module
Public Function NumInpErrChk (TextInput As
TextBox, MinVal As Integer, MaxVal As Integer) As
Boolean
If (Not IsNumeric (TextInput.Text)) Or
(Val (TextInput.Text) < MinVal) Or
(Val (TextInput.Text) > MaxVal) Or
(Val (TextInput.Text) <>
Int (Val (TextInput.Text))) Then
MsgBox "Please enter an integer
between " & MinVal & " and " &
MaxVal & ".", vbExclamation,
"Error!"
TextInput.SetFocus
TextInput.Text = ""
Exit Function
End If
NumInpErrChk = True
End Function
‘
‘And in frmMain…
Private Sub cmdButton_Click ()
If NumInpErrChk (txtMain, 1, 10) Then Print
"Correct!"
End Sub
Reading a text file
Dim Helpfile As Integer
Helpfile = FreeFile
Open “[filename]” For Binary As Helpfile
txtHelp.Text = Input (LOF (Helpfile), 1)
Close HelpFile
Timers
Dim tmr As Single
tmr = Timer
Print Format (Timer - tmr, "0.00") & “seconds.”
Dim tmr As Date
tmr = Now
Do Until DateDiff ("s", tmr, Now) > 1
Loop
Loading & unloading forms
Private Sub cmdButton_Click ()
Load frmHelp
frmHelp.Show
End Sub
Private Sub Form_Unload (Cancel As Integer)
If frmHelp.Visible Then Unload frmHelp
End
End Sub
‘
‘And in frmHelp…
Private Sub cmdOK_Click ()
Unload Me
End Sub
Adding controls at runtime
Option Explicit
Private WithEvents cmdButton As CommandButton
Private Sub Form_Load ()
Set cmdButton = Controls.Add
("vb.commandbutton", "cmdButton")
With cmdButton
.Visible = True
.Width = 2000
.Caption = "Hello"
.Top = 1000
.Left = 1000
End With
End Sub
Private Sub cmdButton_click ()
MsgBox "Hello world!"
End Sub
File handling
‘Creates file 1.dat containing 10 rows of ‘1,4,"Leo"’…
‘
Open App.Path & "\1.dat" For Output As #1
For n = 1 To 10
Write #1, n, Numbers (n), "Leo"
Next
Close #1
‘Reads 1.dat & prints output.
‘
Open App.Path & "\1.dat" For Input As #1
Do Until EOF (1)
Input #1, a, b, c ‘Line Input reads a whole line
at a time, including delimiters.
Print a, b, c
Loop
‘To save eg a map…
‘
Open App.Path & "\1.dat" For Output As #1
For y = 1 To 10
For x = 1 To 10
Write #1, map (x, y);
Next
Write #1,
Next
‘And to read it…
‘
Open App.Path & "\1.dat" For Input As #1
For y = 1 To 10
For x = 1 To 10
Input #1, map (x, y)
Next
Input #1, endofline
Next
Download