Thursday, July 17, 2008

vb questions 7

1) If your user wants to uninstall the application you developed, which
method will you use to make it easy for him
a) Use setup wizard (*)
b) Customize the Setup.exe
2) If you have a progress bar. what propertry would you use to show its
a) Index
b) Value(*)
3) What error do you get if the following code is executed
Private Command1_Click()
Command2.Value = TRUE
End sub
Private Command2_Click()
Command1.Value = TRUE
End sub
Ans : Stack Overflow error
4) How do you create a Public read only and Private Read/Write. The options
were something like
a) Public Get Name()
Name = stname
Private Let Name( stname as string)
stname = Name
b) Public Get Name()
Public Let Name()
c) Private Get Name()
Private Set Name()
d) Public Get Name()
Private Set Name()
5) When a user browses a web page which has a control you developed and the
browser displays a warning. what will you ask your user to do.
Ans : Ask the user to set his browsers security level to none or zero.
6) What event would you use if a user presses F2
7) A ListBox is in a frame. The HelpContextId of the ListBox is set to 0.
When the user presses F1 and the ListBox has focus What happens.
8) If you have a number of controls to distribute over the Web. How would you
decrease the download time for the user.
9) When the following code executes. What will the user see
Public Sub MyTest()
On Error GoTo ErrHandler
Dim X as Integer
MsgBox "XXX"
MsgBox "YYY"
End Sub
Public Sub MyProc()
On Error GoTo MyprocErr
X = X / 0
MsgBox "ZZZ"
End Sub
a) "XXX" Only
b) "ZZZ" Only
c) "XXX", "ZZZ" and "YYY" Only
d) "XXX" and "ZZZ" Only
10) When you are testing your user control. you add a standard exe to your
project group. But the user control in your tool bar is dommed. What should
you do?
11) Which code would you use to create a instance of Form1
a) Dim Frmx as Form1
b) Dim Frmx as New Form1
c) Dim Form1 as Form
d) Set Frmx = GetObject("Project1.Form1")
12) How would you display text in a status bar which has its 2nd panel key
a) Statusbar1.Panel2.Text = "Printing ..."
b) Statusbar1.Panel(2).Text = "Printing ..."
c) StatusBar1.Panel("Panel2") = "Printing ..."
1 . Use Regsvr32.exe to install Active X DLL, EXE, OCX.
To install ActiveX.dll: Regsvr32 dllname
To install Activex.Exe: AX_exename /Regserver
2 Test Activex.EXE (out-of-process) component
2 instances of VB
Test Activex.DLL (in-process) component
Add Standard.EXE and use 1 instance of VB
Debug ActiveX control project
Run Active x control while the client is in design mode
1)When testing a User Control, you add a standard.exe to your project group.
User control in the Toolbox is dimmed. What should you do? Close the User
Control designer and then test again.
4 Advantages of using Watch window:
5 What can be viewed in the local window?
All the variables in the procedure scope
6 Immediate Window:
view, add, change and declare variables and see the result being returned.
7 What Call stack shows?
8 Why the context property in Immediate window is useful?
9 Autoredraw = False only affects line, pset, cicle created at run-time, not
design time. Use Refresh instead of Autoredraw to save system resources.
10 DropHighlight used for drag-and-drop operation on a TreeView and
DropHightlight goes with HitTest in an OLE dragDrop operation
11 ActiveXDocument.Hyperlink.Helpfile
Use Hyperlink object on ActiveX Document, needs a hyperlink-aware container,
e.g. IE4
12 Property procedures e.g. Public Property Get ABC (ByVal... ByRef...
Optional...ParamArry intNum) Those in parantgese are optional argument types.
13 How to declare DLL functions:
14 AsynRead method is used to do asynchronous download. Datatypes to be
downloaded: files, pictures, byte arrays
15 Implements as keyword used in a class module - used for Automation
Implements ABCDE
'ABCDE is a secondary interface created based on the type library's abstract
interface. How to do it? Set reference to the type library
What should be the syntax using Implements keyword?
16 Disadvantage of using Implements keyword:
Can only be used in Standard module;
Need to declare all the public variables, etc.
17 LockEdits = False
Optimistic locking, the record (2k page) be locked when you use the method
LockEdits = True
Pessimistic locking, the record (2k page) will be locked when you use the
method Edit
Get familiar with different situations using LockEdits and understand it.
18 Create private property - read only
Private Property Get ABC (no Property Let nor Property Set)
Create public property - write only
Public Property Let
PropertyChanged "BBB"
19 What can be placed on MDI form?
Picturebox control (not image control)
timer control, Data control, Menu control
20 Public variable declared in a form
Scope : entire application, make reference to form name if necessary
21 Data control's default Recordset type: dynaset-type recordset
22 HelpContextId = 0 is the default. If the HelpContextId of a botton control is set to zero, the container, i.e. frame or form's HelpContextId will be used. If there are no HelpContextID specified in the container, then NO HELP.
23 CommonDialog1.ShowHelp
This requires : CommonDialog1.HelpFile to be set
CommonDialog1.HelpCommand to be set
maybe a reference to CommonDialog1.HelpKey
24 Change the BackColor of UserControl's label1
Use Ambient Properties
25 In a DragOver event, how to change the backcolor of the label which is
being dragged over the target?
Source.BackColor = vbRed
26 Active X files for internet distribution:
Inf file equivalent to Setup.lst file
Inf file contains references to files, support files
.cab file (contains ActiveX.dll or .exe, inf file that is equ. to Setup.lst
file with links to support files, sec. cab files, space for digital signing)
.vbd file
.htm file
27 How to reduce the time for downloading on Internet an Active X componet?
Create separate secondary .cab files.
Users may already have these secondary .cab files on the system or the
secondary .cab files can be downloaded from Microsoft's web site.
28 StatusBar panels - is 1-based?
Get familiar with how to show a string in, for instance, the 2nd panel of a
29 Toolbar
Properties: Button.Key and Button.Index
30 What event will be fired when you move from one record to another in a
31 How to Pass Null to DLL
ByVal as String
pass vbNullString
32 Conditional Compilation
Can use literal statements except the IS operator
33 Where do you define conditional compiling variables?
Command line
Project Properties dialog box (under the Make tab)
In code
34 Dim x As Integer
What event gets fired? Initialize
35 How to convert an ActiveX.DLL to multithread?
Make it ActiveX. EXE
36 How to raise an event"
first to declare it, use the Event keyword, then Raise it. e.g. RaiseEvent
ABC (arguments)
37 How to add a control to a web page? By scripting
38 Press F2, what event is fired? KeyDown
39 What property of ProgressBar to show status? Value
40 Under what situation will you have this error message "Out of Stack
41 With TreeView control, use Add method to add a child node.
It goes with "Relationship" not "Relative", know the keyword tvwFirst,
vwLast, etc.


42 Hyperlink object, GoForward and GoBack

Webrowser, GoHome and GoSearch


43 How to pass Null pointer to a C function that is expecting a character

VB byte type?


44 GlobalMultiuse

For ActiveX.DLL and ActiveX.EXE

Enable you to use the properties as if the component is an intrinsic
controls, there's no need to declare the variables, one instance of the
class created for multiple client use.


45 DBGrid's column property is 0-based


46 Dynaset and filter property


47 Setup a standard.exe, VB5DEP.INI is the dependency file


48 An error occurs in a component that you wrote, how to notify client:

Err.Raise number


49 How to create a license package for ActiveX control licensing

Use LPK_Tool.exe


50 How to dynamically create or remove controls?

Set up control arrays at design time, at run time, use Load and Unload
control statements.

e.g. Load ABC(index#)

e.g. Load mnuFile(2) for dynamic menu


51 When can you add watch statements?

At design time or break mode.


52 What property to set if you want both menus (from the object and from the
container) shown ?

NegotiageMenus on the container


53 How do you implement a sink event of a class using a variable?

Visual Basic 6.0 Study Guide


Program Structure

A typical application consists of one or more modules: a form module for
each form in the application, optional standard modules for shared code,
and optional class modules. Each module contains one or more procedures that
contain the code: event procedures, Sub or Function procedures, and Property

Startup Form can be set in Project Properties. Sub Main() can only be in a
standard module. To display a splash screen, use a Sub Main procedure as
startup object and use the Show method to display the form:

Private Sub Main()

frmSplash.Show ' Show the splash screen.

… ' Add startup procedures here.

frmMain.Show ' Show the main form and unload the splash screen.

Unload frmSplash

End Sub

Three ways to end an application:
Single Form

Multiple Forms

Private Sub cmdQuit_Click ()

Unload Me

End Sub

Private Sub Form_Unload (Cancel As Integer)

Dim i as integer

' Loop through the forms collection and unload

' each form.

For i = Forms.Count – 1 to 0 Step - 1

Unload Forms(i)


End Sub


End statement

Ends an application immediately: no code after the End statement is executed,
and no further events occur. Object references will be freed, but if you
have defined your own classes, Visual Basic will not execute the Terminate
events of objects created from your classes.

Life Cycle of Visual Basic Forms

1.Created, but not loaded. (Initialize) This is the only state all forms
pass through. 2.Loaded, but not shown. (Load) Create Controls. Assign hWin,
hDC. 3.Shown.

(Resize) - Occurs when an object is first displayed or when the window state
of an object changes. (For example, a form is maximized, minimized, or

(Activate) - Occurs when an object becomes the active window.

(Paint) - Occurs when part or all of an object is exposed after being moved
or enlarged, or after a window that was covering the object has been
moved. 4.Memory and resources completely reclaimed.

(QueryUnload) – Prompt user for saving.

(Unload) - Remove from Forms Collection. Module-level variables may still

The only way to release all memory and resources is to unload the form and
then set all references to Nothing. Set Form1 = Nothing


Executing the End statement unloads all forms and sets all object variables
in your program to Nothing. However, this is a very abrupt way to terminate
program. None of the forms will get their QueryUnload, Unload, or Terminate
events, and objects created will not get their Terminate events. 5.Unloaded
and unreferenced while a control is still referenced.


Object Concept

Objects in Visual Basic are created from classes; thus an object is said to be an instance of a class. The class defines an object’s interfaces, whether the object is public, and under what circumstances it can be created. Descriptions of classes are stored in type libraries, and can be viewed with object browsers.

To use an object, you must keep a reference to it in an object variable. The type of binding determines the speed with which an object’s methods are accessed using the object variable. An object variable can be late bound (slowest), or early bound. Early-bound variables can be DispID bound or vtable bound (fastest).

A set of properties and methods is called an interface. The default interface of a Visual Basic object is a dual interface which supports all three forms of binding. If an object variable is strongly typed (that is, Dim … As classname), it will use the fastest form of binding.


Using Code Editor

In a form module, the list includes a general section, a section for the form itself, and a section for each control contained on the form. For a class module, the list includes a general section and a class section; for a standard module only a general section is shown.

Class modules list only the event procedures for the class itself — Initialize and Terminate. Standard modules don't list any event procedures, because a standard module doesn't support events.

Breaking and combining statements

Text1.Text = "Hello" : Red = 255 : Text1.BackColor = _


Declaring Variables

Dim variablename [As type]

••Declaring a variable in the Declarations section of a form, standard, or class module, rather than within a procedure, makes the variable available to all the procedures in the module. •Declaring a variable using the Public keyword makes it available throughout your application. •Declaring a local variable using the Static keyword preserves its value even when a procedure ends.

Implicit Declaration - You don't have to declare a variable before using it.

Explicit Declaration - Using "Option Explicit"

•The Option Explicit statement operates on a per-module basis; it must be placed in the Declarations section of every form, standard, and class module for which you want Visual Basic to enforce explicit variable declarations. If you select Require Variable Declaration, Visual Basic inserts Option Explicit in all subsequent form, standard, and class modules, but does not add it to existing code. You must manually add Option Explicit to any existing modules within a proje<

Scoping Variables

Depending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable.




( Dim, Static )

Variables are private to the procedure in which they appear.

Not applicable. You cannot declare public variables within a procedure.


( In Declaration Section )

Variables are private to the module in which they appear.

Variables are available to all modules.

Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing. At the module level, there is no difference between Private and Dim. You can't declare public variables within a procedure.

Static Function or Sub will make all the local variables in the procedure static regardless their declaration inside.

Constant has the same scope rule as variable does.

Friend members is suitable in the ActiveX components. Friend functions are not part of an object's interface. They can't be accessed by programs that use the component's objects. They're only visible to all the other objects within the component to allow safe internal communication within the component.

Because Friend members aren't part of an object's public interface, they can't be accessed late bound — that is, through variables declared As Object. To use Friend members, you must declare variables with early binding — that is, As classname.

The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn't appear in the type library of its parent class, nor can a Friend procedure be late bound.

Friend makes the procedure visible throughout the project, but not to a controller of an instance of the object.


Name Conflicting and Resolving

The forms and controls can have the same name as a restricted keyword. To resolve conflict, using:

•MyForm.Loop.Visible = True ' Qualified with the form name.

[Loop].Visible = True ' Square brackets also work.

Within the form module, local variables with the same names as controls on the form shadow the controls.

To resolve conflict, using: a reference or keyword Me

Private Sub Form_Click ()

Dim Text1 ' Assume there is also a control on the form called Text1.

Text1 = "Variable" ' Variable shadows control.

Text1.Top = 0 ' This causes an error!

Me.Text1.Top = 0 ' Must qualify with Me to get

End Sub

A variable in the module cannot have the same name as any procedures or types defined in the module. It can, however, have the same name as public procedures, types, or variables defined in other modules. In this case, when the variable is accessed from another module, it must be qualified with the module name.

Constant Name is referenced in case of collision depends on which object library has the higher priority.

To resolve conflict, using: [libname.][modulename.]constname


Data types

Dim EmpName As String * 50

Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private. You can assign a string to a numeric variable if the string represents a numeric value.

The default value of Boolean variable is False.

Object variable is actual a 32-bit pointer referring to an object within an application or within some other application. Using the Set statement to refer to any actual object recognized by the application.

•Dim objDb As Object ‘or Database

Set objDb = OpenDatabase("c:\Vb5\Biblio.mdb")

By default, if you don't supply a data type, the variable is given the Variant data type. A Variant variable is capable of storing all system-defined types of data. You don't have to convert between these types of data if you assign them to a Variant variable; Visual Basic automatically performs any necessary conversion. For example:

Dim SomeValue ' Variant by default.

SomeValue = "17" ' "17" (a two-character string)

SomeValue = SomeValue - 15 ' numeric value 2

SomeValue = "U" & SomeValue ' "U2" (a two- character string)

••If you perform arithmetic operations on a Variant, the Variant must contain something that is a number. •If you are concatenating strings, use the & operator instead of the + operator. •Variants can contain three special values: Empty, Null, and Error.

•Empty is used to see if a value has ever been assigned to a created variable.

•Null is commonly used in database applications to indicate unknown or missing data. Null will propagate through expressions involving Variant variables. Variables are not set to Null unless you explicitly assign Null to them.

•Error is a special value used to indicate that an error condition has occurred in a procedure. Error values are created by converting real numbers to error values using the CVErr function.

Note: A variant always takes up 16 bytes, no matter what you store in it. Objects, strings, and arrays are not physically stored in the Variant; in these cases, four bytes of the Variant are used to hold either an object reference, or a pointer to the string or array. The actual data are stored elsewhere.

•It can only be used in as the final argument in an argument list. •It represents an optional array of variant Data type •It cannot be used with ByVal, ByRef or Optional keywords •It is used in these contexts:
••Declare Statement •Function Statement •Property Get Statement •Property Let Statement •Sub Statement

You create a user-defined type with the Type statement, which must be placed in the Declarations section of a module.

User-defined types are always passed by reference.

•Public Type udtAccount

Number As Long

Type As Byte

CustomerName As String

Balance As Double

End Type

Enumeration data type

Public Enum WorkDays


Sunday = 0






Invalid = -1

End Enum



Dim Sums(20) As Double ' 21 elements. The default lower bound is 0.

Dim Counters(1 To 15) As Integer

Dim MultiD(3, 1 To 10, 1 To 15) 'multi-dimension

Dim DynArray() 'dynamic array

ReDim DynArray(4 to 12) 'is an executable statement, can appear only in a procedure

ReDim Preserve DynArray(UBound(DynArray) + 1) 'reserve the old values

•ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10) 'Error: Only the upper bound of the last 'dimension in a multidimensional array can be changed

You may want to use a collection instead of array if you're working with a small, dynamic set of items.

A Collection object stores each item in a Variant. A Collection object has three methods (add, item, remove) and one property (count). Collection are not polymorphic. Forms collection contains all of the currently loaded Visual Basic forms in the program. Collection class contains anything that can be stored in a Variant. Thus the Collection object can contain an object or an integer, but not a user-defined type.

control array

A group of controls that share a common name, type, and event procedures. Each control in an array has a unique index number that can be used to determine which control recognizes an event.

There are three ways to create a control array at design time:

Assign the same name to more than one control.

Copy an existing control and then paste it onto the form.

Set the control's Index property to a value that is not Null.

Note: You must create menu control arrays in the Menu Editor.

At run time, use:

Load Object(index%)

Unload Object(index%)

•The control must be created at design-time to be ready loaded at run-time. You can use the Unload statement to remove any control created with Load. However, you cannot use Unload to remove controls created at design time.


Declaration Statement

[Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

Sub procedures are by default Public in all modules, which means they can be called from anywhere in the application. There are two types of Sub procedures, general procedures and event procedures.

Sub ButtonManager(Button As Control) ‘general procedure, usually in bas. module

Private Sub cmdUp_Click() ‘event procedure

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.

Call MyProc (FirstArgument, SecondArgument)

MyProc FirstArgument, SecondArgument

Function has return value.

There are three ways to call a Function procedure:

X = functionForX

Call function(x) ‘will throw away return value

Function x ‘will throw away return value


Sub ListText(ByVal x As String, Optional y As _Integer = 12345)

Using the ParamArray keyword allows you to specify that a procedure will accept an arbitrary number of arguments.

ParamArray is used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. The ParamArray keyword can't be used with ByVal, ByRef, or Optional.

Named argument for many built-in functions, statements, and methods:

Function ListText(strName As String, Optional strAddress As String)

List1.AddItem strName

List2.AddItem strAddress

End Sub

Private Sub Command1_Click()

ListText strAddress:="12345", strName:="Your Name" ‘in reverse order

End Sub

Control Structure

For Each element In group

Next element

This is helpful if you don't know how many elements are in a collection.

••For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser. •For arrays, element can only be a Variant variable. •You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.

•Exit For … Exit Do … Exit Sub … Exit Function ‘exit control structure


Properties that you can set and get at run time are called read-write properties. Properties you can only read at run time are called read-only properties.

There are some common cases in Visual Basic where one object contains other objects. Forms, Controls, Printers.

Three ways to refer a collection member:




You can use the Container property to change an object's container within a form.

The following controls can contain other controls:
••Frame control •Picture box control •Toolbar control (Professional and Enterprise editions only)


Each menu you create can include up to five levels of submenus. Ctrl+E: Menu Editor

A menu control array is a set of menu items on the same menu that share the same name and event procedures. Each menu control array element is identified by a unique index. Use a menu control array to:
••Create a new menu item at run time when it must be a member of a control array. For example, a menu control array may be used to store a list of recently opened files. •Simplify code, because common blocks of code can be used for all menu items.

Elements of a menu control array must be contiguous in the menu control list box and must be at the same level of indentation. When you're creating menu control arrays, be sure to include any separator bars that appear on the menu.

What is the restrictions of dynamically created menu items?

Cannot have shortcut keys

Cannot be used for a WindowList

Must be menu control array elements

Pop-up menu

Private Sub Form_MouseUp (Button As Integer, Shift As _

Integer, X As Single, Y As Single)

If Button = 2 Then ' Check if right mouse button was clicked.

PopupMenu mnuFile ' Display the File menu as a pop-up menu.

End If

End Sub

•Any code following a call to the PopupMenu method is not run until the user selects an item in the menu or cancels the menu. Only one pop-up menu can be displayed at a time. While a pop-up menu is displayed, calls to the PopupMenu method are ignored. Calls to the PopupMenu method are also ignored whenever a menu control is active.

Menu and toolbar negotiation will occur only for insertable objects that support in-place activation.

1.The NegotiateMenus property does not apply to MDI Forms. 2.The NegotiateToolbars property applies only to MDI forms.

There are three ways to set conditional compilation constants:
•Project Properties dialog box - Public to all modules in the project •Command line - Public to all modules in the project

•vb6.exe /make MyProj.vbp /d conFrenchVersion=–1:conANSI=0

••#Const statement in code - Private to the module in which they are declared.

•- Only conditional compiler constants and literals can be used in expression.

Conditional compilation can use literal statements except for IS operator.

Your Title