What's New
Dev Tools
Site Map

1. Starting Visual Basic Concepts & Terminology

Visual Basic terminology is provided in the table below. It includes "translations" for PowerBuilder (PB) users.

VB Term Description PB Term
1.1 Structure    
Project A project is a group of Forms and modules that comprise an application. Application
Form It is a window. A Form includes its own variables, events and functions as well as its controls (along with events for those controls). It is stored as with ".FRM" extension or ".FRX" when in binary format. Window
Modules Modules are objects that hold variables (including global variables) and functions that are not specific to a Form. It can be used to encapsulate re-usable functions that might be used across several Forms or even several applications. Global.BAS is the standard generic module – it is usually shared amongst several VB apps. Generic User Object
Variables - Variables can be local Dynamic ("Dim") where they are only available to the script and created & destroyed with script
- they can be static ("static") where they are still local to the script but their value is "remembered" between calls to script
- they can be declared in the Form’s "general" declarations and available to all controls / subprocs on the Form
- they can be declared as "global" in a module, then they will be available throughout project (all modules, all Forms)
- variables can be public (available outside proc) or private
- arrays can be given a fixed or variable size. If they are given a fixed size, they can be resized ("ReDim") during runtime (can use the "preserve" option, if array contents need to remain)
- constants are also supported.
local variable

no equiv.

instance var.

App global

variables can be public, private or protected


Pointers Pointers are not supported – can only simulate concept by creating structure/arrays and managing them manually. pointers (supported)
1.2 Main Controls    
Label Place for static text on a Form. Text
Text Box An input or edit field (it can be tied to a DB field via a Data Control) resembles single-line-edit or DW column
Edit Mask Control The mask lets you mask an input field (e.g. dashes in phone number) and set a display format (e.g. add dollars and commas for numbers when focus is lost).

Mask also lets you mimic m/f app behaviour and automatically move to the next field when this field is full (see AutoTab property). There is no equiv. to AutoTab on textbox.

Input Mask, Display Format

No AutoTab equiv.
Frame Provides a method to logically group controls (e.g. several radio buttons or checkboxes) GroupBox for windows & now DW
Command Button Standard command button with click event. Command Button
Control Array Keeps a list of controls (e.g. checkboxes or radio buttons) so they can be passed to a routine for processing – the same script might be used for the whole group of controls.  
Combo Box Control (typically drop down) that lets the user either select an item from a list or just type in a value. Events include change, click, etc. enterable DDDW or DDDL
List Box Selectable (but not enterable) list that displays a number of entries. The list is displayed without having to click a dropdown arrow. List Box
Progress Bar Control Shows user visual progress of an action (e.g. something like data movement that takes time to complete). Progress Meter
Timer Event Starts events behind the scenes (based on desired interval in 1000ths of a second). Timer function
Drive ListBox, Directory ListBox, File ListBox Lets user specify a windows file location. Windows API?
Shapes Lines, squares, ovals, etc. These are just visual – they don’t hold controls. Shapes
Picture Box A container that can contain a picture. User can also draw on it. Picture
Image Control to show bitmaps, predefined VB pics, etc. Similar to picture but user cannot draw on it (so requires less memory) Picture
Toolbar This must be built up manually, grouped together and manually tied to menu items (one-by-one). Menu item toolbar (automatic)
Status Bar Status bar can be added to the bottom of window and its contents can be fully controlled/defined. Microhelp: more automatic, less flexible than VB.
Tab Control Control that holds multiple tab pages (commonly known example is the MS Excel options tab). Tab Control
Rich Text Control Control that lets user enter text, including bold, italics, font size, font style, margins. Rich Text Control
Common Dialog Control VB provides what it calls its "common dialog control" to provide access to a number of standard Windows dialogs (Open File dialog, Save File dialog, Print Setup dialog, Windows Help dialog, Select Font dialog and Select Colour dialog). Separate PowerScript functions for first four.
OLE Any OLE compliant object can be placed on a Form (e.g. Word 6 to enter data, Excel spreadsheet, etc.). Placing another control on a VB Form makes VB an "OLE client".
A VB App can also be made into an object and act as an OLE Server to other Apps.
OLE – PB supports it but not quite as easily as VB
Dialog Box Brings up standard windows dialog boxes (e.g. opening file, saving file, printing, choosing font or colour)  
1.3 Data Access    
Data Control Device that allows a data query to be tied to controls (e.g. to text boxes, masks) on a Form. Each Data Control does its own login/connect to DB. resembles PB DataWindows (similar ease of setup)
Data Access Object (DAO) Device that provides an OO interface to the DB. It has many similarities and shared commands with a Data Control but it gives more flexibility and control than the Data Control (DOAs also require more effort to create and use).

DAOs will perform faster than Data Controls (can consolidate App into single DB login/connect) but they are still slow accessing non-MS Access type databases (e.g. Oracle, SQL Server) – VB suggests using Remote Data Objects (RDO) in the Enterprise Edition to get a faster interface to these "other" DBs.

DAOs don't automatically move data to/from controls on the Form. All this is now manual. Also appears that if DAO is used (at exclusion of Data Controls), then any listboxes and comboboxes would have to be manually loaded. In other words, runtime and development efficiency is a real tradeoff.

resembles DWs but DAOs require more manual movement of data to/from controls.

PowerBuilder has native interface to many DBs (don't have to change underlying DWs).

ActiveX Data Objects In Visual Basic 6, Microsoft replaced earlier database connection strategies Data Access Object (ADO) and Remote Data Objects (RDO) with a new preferred and new connection technique that has similarities with DAO but is more powerful.  ADO is discussed elsewhere on this site. ADO's are closer to the power/ capability of a DW compared to DAO or RDO.
1.4 Major Events    
LostFocus SubProc Field-level validation code is added on a control-by-control basis, unlike PB where the code would usually be grouped together under the datawindow’s ItemChanged event. ItemChanged
Main Textbox Events - Change (every keystroke)
- Get Focus (when control receives focus)
- Lose Focus (when control loses focus)
- no event fires when text is changed, when leaving control
- EditChanged
- GetFocus
- no PB equv.
- ItemChanged
Load / Show


Load command creates an instance of a Form, causing load event. Show makes it visible (as modal or non-modal), causing activate event. A Form's Activate/Deactivate event fire each time focus moves to/from that Form, while in the application. Open command
Open event
no equiv. event
Unload / Terminate Unload destroys an instance of a Form, causing unload event. Set Formx = Nothing, causes terminate event. Close command
Close event
Query Unload This event lets you know how/why Form was closed. To stop the closing (setting Cancel=True) -- e.g. if there are unsaved changes. CloseQuery
Control Resizing Windows and control are resizable. They have resize events which can be used to react to any resizing (e.g. adjust control size to reflect change Form size). Resize events.
1.5 Misc.    
Editor Colour-coded editor which syntax checks each line as it is entered (this can irritating when a line is only half finished). Indentation must be done manually and is awkward to get right/consistent, at first. Colour coded editor with automatic indentation. It checks syntax as script is left.
Conversion Functions Val converts a string to a number (discarding chars)
Str converts a number to a string (Format fcn is more comprehensive)
CDate converts a string to a date
Long or Int fcn
String fcn
Date fcn
Special Characters / Special Values underscore "_" tells VB that a line is continued on the next line
single quote " ' " tells VB that the rest of the line is a comment
ampersand " & " tells VB to concat. strings or strings / numbers
plus " + " can also be used to concatenate strings
True / False equates -1 / 0 respectively
& - line cont'd

//, /*…*/ -com't

+ -for concat.

Input Box Invoked in runtime (like MsgBox) but allows input of a string no equiv.

2. Visual Basic: How To

Description of how to perform common actions in Visual Basic development.

VB Item How To
2.1 Structure  
Create a Project Do File-New Project (and indicate standard EXE in VB5). Next, go to Tools-options, Project and set appropriate project options (e.g. .whether project and/or properties box should "stay on top"). It is best to put the objects for each project into a dedicated project directory.
Using Properties Box Sits at the side of the Form (always partially visible). Invoked by clicking on (not right mouse). Once on box, can switch to properties of most controls on Form by selecting from control list at top of box – doesn’t work for individual tab pages.
Some of the more complex objects (e.g. combo box, masks) have additional properties that can be set with right-mouse, properties on the object itself.
2.2 Controls  
Adding a Control Select object from control toolbar. On a Form, click and move mouse to specify initial control size. To add an item not on toolbar, check it under Tools-Custom Controls.
Labels Labels can be set to autosize property to adjust to size of text in label (i.e. like PB default)
Masks: for Numbers, etc. While you can use a text-box control for numbers, it is better to use the mask edit control for numbers. The mask lets you automatically disallow characters and also format numbers as needed (e.g. with comma, dash-separated, etc.). In mask, use # for mandatory number, 9 for optional number and A for alphanumeric. Other characters (e.g. "-") will be considered literals and appear "fixed" in field.
Using radio buttons 1. Setup frame first, then add radio buttons inside frame.
2. Check if radio button is set:
If optFirstOption.Value Then
… do code for first radio button
Elseif optNextOption.Value Then
… do code for next radio button
Creating a Toolbar a) Create Image list – tying pictures to image list, one-by-one.
b) Create toolbar outline and tie it to Image List. While tying to image list, give an index # to each spot in the toolbar (1, 2, …)
c) In button clicked event (for toolbar?), for each index value (1, 2, …), invoke the corresponding menu clicked event.
Creating a DB Grid Create grid and add first column or two. To add more columns, right-mouse and edit. Edit lets you resize columns and right-mouse insert them, where desired. You can include/hide row and column separators and hide/show row/column headings. These changes can make the grid look more like a true grid or a standard list.
Creating a DB Combo Box When Other Fields in Record are from Data Control:

Steps to add combo box into "main table" (where combo box is sourced from "Code Table" and shows Code Table descriptions in the dropdowns):

a) add initial main table data control and non-combo box field controls, as normal
b) add "code table" Data Control to Form (tying its RecordSource to code table in DB)
Add DB combo box to Form and do the following to its properties:
c) set its RowSource property to "code table" data control
d) set its ListField property to code desc
e) set its DataSource property to "main table" Data
Control (i.e. where to make updates)
f) set its DataField property to "main table" code id (i.e. where to make updates)
g) set its BoundColumn property to the join field (i.e. the code id)

When Other Fields in Record are from Data Access Object:

- same steps as above, except skip step e, f. Also, step a) involves setting up DAO instead of Data Control (see DAO How-To section).

Note: on the combo box, use right-mouse/properties and choose "drop down list" and "extended matching" so that the user can type in the code (using chars entered, this does a multi-char match while "basic matching" does just uses first char to position & move in list). The default of "combo box" and "basic matching" forces the user to enter the code id, if they want to type in the field (i.e. when not using dropdown).

Note 2: ".Text" property for dbcombo box is current "ListField" value (i.e. typically code desc) while ".BoundText" is current "BoundColumn" value (i.e. typically code id).

Add Picture Box Put control onto window and then select bitmap (or whatever) to add into it.
Creating a Control Array Create radio button and then copy it – say "yes" to control array and they will become a control array. Don’t think you can make items into a control array, after the fact.
Scrollbar Can be used to control something on a continuum (e.g. colour shading?). Use scroll event to add code.
Slider Bar Similar to scrollbar but shows discrete hatch marks (e.g. 10ths) along its length.
Rich Text Control Can use "Key up" events to add extra commands to rich text control (e.g. skip to next word, etc.)
OLE First go to Tool-Reference and check the OLE tool you want to imbed (e.g. Office 95). You can use the Object Browser to view the objects provided by the type library that you have referenced. You can obtain help for that object right from VB – supposedly by pressing F1 on highlighted object name.

To Dynamically Invoke an OLE Object on a Form (and run commands):
MS EXCEL Example

Dim x1 as Object 'declare this at Form level
Set x1 = CreateObject("Excel.Application")
… various object-specific commands … (see VB Sample Code)

If object is not closed in code, user can then "take over" to save, print, etc.

To Add an OLE Control onto a Form:

a) Put OLE onto Form
b) Insert object (specify type)
c) Choose type of link: "Linked" (to save by OLE-object) or "Embedded" (to save inside VB)
d) Specify if drag & drop allowed (e.g. to drop items like bitmaps into OLE object).

To use the OLE control, the user seems to have to right-mouse edit to get simple editing abilities or right-mouse open to open/save documents within the tool.

2.2b Data Control  
Adding a Data Control & fields (manual method) a) Add controls onto Form (e.g. various text boxes).
b) If data for more than one field needed, write a DB query to select desired data.
c) Create Data Control, specifying RecordSource as a whole table or SQL or DB query – Data Control can be left visible for primitive (but ugly) scrolling.
d) Finally, tie each text box to a field in the Data Control (first tying it to the Data Control "DataSource", then the specific field "DataField"). Step a) can be deferred until now and this step done all at once.
Data Form Designer (automatic method to add Data Control, etc.) Pick a table and select desired fields. The designer then paints a window with those fields, the Data Control, as well as Add, Update, Delete, Refresh buttons --> like PB DW painter, except one-table only(?) and it gives you the buttons automatically.

Chief problem with the Form produced is that all controls get meaningless default names. To change the data control name to a meaningful one (not Data1) entails fixing code for the default buttons, the fields, etc. You also have to change the DataSource for all text controls (to refer to meaningfully named DataControl).

2.3 Data Access  
Data Access Object (DAO) A. Under Tools-References, be sure to set up "Microsoft DAO 3.0 Object Library" if using 32-bit applications.
B. See 15-page writeup on DAOs from VB4 tutorial CD for details.
In brief, here is how to setup a window that maintains one row at a time, using DAO:

1. Connect to DB, probably as App starts
Set db = OpenDatabase("Home_vb_DB.mdb")
2. Setup RecordSet (e.g. tablename or SQL Select or query), usually in form load

Set rs = db.OpenRecordset("Person_1")
3. Position to start of recordset, probably in Form load
f_SetFields <-- write this to move fields from recordset to Form Controls

4. Write f_SetFields (from rs), f_GetFields (to rs), f_ClearFields to manually move data between recordset and Form fields – see sample code.

5. Write button code (Add, Update, Delete) – see sample code.

6. Code MoveNext, MovePrevious, MoveFirst, MoveLast buttons – see sample code.

Queries that take Parameters (query accessed through DAO) 1. Define Query in Database, including its parameters – my query called FindName
Use the Parameters statement followed by the Select (or Insert, etc.) –
see code sample.

2. Write VB code (probably generally in Form Load or Search button)
- declare QueryDef variable and then assigning to query
Q = db.QueryDefs("QueryName")

- assign parameters to the query -- assignment, no set.
Q.Parameters("LastName") = sLName

- Finally, assign the recordset to the Query OpenRecordSet
Set rs = Q.OpenRecordset

Queries that take Parameters (query accessed through Data Control) Same method (and code) as above, adding one more line at end to assign DataControl recordset to "rs" variable defined above, as follows:
Set datPerson.Recordset = rs

Note: you can't provide the name of the parameterized query to the Data Control Record Source in design (it won't even show up in RecordSource dropdown). In other words, you'll have to "fake out" a record source that retrieves, at least, the fields that you need to design time – usually the fields that correspond to bound controls (you might get these fields in RecordSource in design by selecting the whole table or, if it's big, creating a query that will intentionally return nothing using a restrictive Where Clause: e.g. Where 1=2).

Inline SQL 1. open db, probably in app open: Set db = OpenDatabase("Home_vb_DB.mdb")

2. assign sql to a variable: mysql = Select * from bob (or Insert xx into Bob)

3. To execute "action" query: db.execute mysql (e.g. Insert, Update, Delete) to indicate how many record affected (for action query), use db.RecordsAffected.

4. To execute "non-action" query (Select): set rs=db.OpenRecordset(mysql, dbOpenDynaset)

To check data returned from SQL, do rs.MoveFirst, rs.MoveNext to move to needed row(s) and use: rs("desc") to get particular columns from recordset.

Including a Variable in a Select Statement You might choose to dynamically change sql for a Data Control to get the desired rows (instead of predefining a query that takes parms).

dc_x.RecordSource = "Select a, b, from T where c =" & pnum Number

dc_x.RecordSource = "Select a, b, from T where d =' " & pchar & " ' " char

2.4 Major Events  
Events to trap when value in control has been changed (e.g. validation at control level). Since there is no equivalent of PB’s ItemChanged (fires only when value has changed), it needs to be handled programmatically. Declare "IFlag" as Integer in Form’s general declaration (can reuse this variable across both events and controls).

- In GetFocus, set IFlag = 0
- In Change, set IFlag = 1
- In LostFocus, "IF IFlag = 1 THEN
… code for when item is changed.

** it appears that you've already lost focus by the time this event fires so you have to set focus back to get the user to fix it. Use a global like "validation-in-progress" to ensure you don't get infinite loops resetting focus. See code sample.

DB Grid Control Events 1. Click: fires before focus moves to new cell. The "current row/column" are the row & column before this cell was clicked.

2. Row/Col: fires when moving into a new cell (but not when selecting a row). The "current row/column" are the row/col just clicked.

3. SelChange: fires when a row (or column) has been selected for a grid (i.e. selected at the "side"). The "current row" is the row just selected.

Invoke a Command Button Click Event cb_Exit.Value = True (this "value" somehow maps to the clicked event)
2.5 Misc  
Debugging 1. To set breakpoints: in normal edit mode, get to desired line and hit "toggle breakpoint" button to get a breakpoint (more breakpoints can be added before or during debugging). Breakpoints can be removed one at a time or by choosing Run-Clear All Breakpoints

2. To look at variables (or expressions):
a) find debug window (a small pop-up) and type "Print sText" (i.e. where sText is the variable of interest). To redo an earlier Print, put cursor in that line, hit Enter.

b) choose "Tool-Add Watch" and enter a variable-name to watch. If debug window is large enough, you can see the value of that variable (or expression) as you hit breakpoints or step through code.

3. Stepping: "Step Into" button steps to next line and into a procedure, if a procedure is being called. "Step Over" button steps to the next line treating a procedure call as a single line.

4. Skipping Over/Back: Put cursor on line you want executed next and choose Run-Set Next Statement. That line will be executed next.

RunTime Error Handling "On Error" enables an error trap: it indicates what label (or procedure) to jump to should a runtime error occur (e.g. low on memory, diskette not ready) – a complete list is under Trappable Errors in help. Resume statement tells code where to restart executing after error handling (e.g. "Next" statement or another specific label) – can only resume within same proc (see sample code). The trap remains in place until the procedure is done (or until it is explicitly deactivated).

Which Error routine is invoked? If there was an "On Error" in the current proc, that one is executed. Otherwise, it goes back up the calling chain to execute the nearest parents' "On Error" (if any).

The Err object has properties to diagnose the error (it contains last found error, until it is explicitly reset).

In error handling, you might check for a situation or two that you can anticipate (and that the user might take corrective action to fix) and then have a "Case Else" to simply log the error and then do some sort of nice application shutdown.

Alternatively, you can set "On Error Resume Next" to basically ignore error but then explicitly check Err object (as part of your regular code flow) on the next line.

Create Executable For clean EXE, first leave VB and come back in. Then, choose File-Create Executable and VB lets you know of problems, if any, during the creation.
Crystal Reports Single Table Report

a) Get into Crystal reports from VB add-in menu. (ignore spurious errors that Crystal reports mentions for queries).
b) choose File-New to create a new report, then select report style.
c) after choosing DB, drag-and-drop fields (from a table) in DB field pop-up to the report form (use right mouse to change fonts/formats for fields on report).
d) do print preview to see if report seems correct. If so, save it with ".rpt" extension.

Tie Report into VB App

a) go to tools-custom controls and pick Crystal reports. Then from toolbar, select Crystal reports and place it on the Form.
b) use right-mouse, properties to select the report for the control
c) you can setup a command button (or menu item) to invoke report, with code like:

'dynamically tie to report
crEmployee.ReportFileName = "c:\vb\empl.rpt"

'direct to printer (0 for preview, 2 to save to file)
crEmployee.Destination = 1

'sends report to destination
iResult = crEmployee.PrintReport
If iResult = …

Multi-Table Report

a) go to Crystal report DB menu and define links between tables (if links not already defined in DB itself)
b) now create report by selecting fields from either table.

Other Visual Basic Topics

Copyright Woodger Computing Inc.