Está en la página 1de 26

1. How long have you programmed in VB and how would you rate yourself (1-10)?

2. What does the statement DIM bManager as ... tell you?


Declaring Variables

To declare a variable is to tell the program about it in advance. You declare a variable with the Dim
statement, supplying a name for the variable:
Dim variablename [As type]
Variables declared with the Dim statement within a procedure exist only as long as the procedure is
executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a
variable in a procedure is local to that procedure — that is, you can't access a variable in one procedure
from another procedure. These characteristics allow you to use the same variable names in different
procedures without worrying about conflicts or accidental changes.

3. What is the difference between Exec and ExecSQL? (wouldnt this be dependent on data access? Ie ADO
use different method than DAO)
Executes a system procedure, a user-defined stored procedure, or an extended stored procedure.
Also supports the execution of a character string within a Transact-SQL batch.

4.What must the last statement in an exception handler be?

Statement Description
Program execution resumes with the statement that caused the error or the
most recently executed call out of the procedure containing the error-
Resume [0]
handling routine. Use it to repeat an operation after correcting the
condition that caused the error.
Resumes program execution at the statement immediately following the
one that caused the error. If the error occurred outside the procedure that
Resume Next contains the error handler, execution resumes at the statement
immediately following the call to the procedure wherein the error
occurred, if the called procedure does not have an enabled error handler.
Resumes program execution at the label specified by line, where line is a
Resume line line label (or nonzero line number) that must be in the same procedure as
the error handler.
Triggers a run-time error. When this statement is executed within the
error-handling routine, Visual Basic searches the calls list for another
Err.Raise Number:= number error-handling routine. (The calls list is the chain of procedures invoked to
arrive at the current point of execution. See the section, "Error-Handling
Hierarchy," later in this chapter.)

5. What is the difference between a property a method and an event? Give an example of each.
1. Text1.color ------ is a property (Mostly to change the appearance )
2. Text1.text ------- is Method (Mostly to set values which r not graphical)
3. button 1. Click -- is event (Event is the result of user interaction with application)
6. What is a variant data type and when would you use it?
Variant will store all the different possible VB data received at one place
7. Why is it not good to use a variant data type?
Using variant rather than a specific data type is slower because of conversions needed and takes up more
memory because additional over head
8. What is the difference between a Dynaset and Snapshot and how would you create one? (we dont use
snapshot in VB5+)
A dynaset-type Recordset object is a dynamic set of records that can contain fields from one or more tables
or queries in a database and may be updatable. In an ODBCDirect database, a dynaset-type Recordset
object corresponds to an ODBC keyset cursor.
Remarks
A dynaset-type Recordset object is a type of Recordset object you can use to manipulate data in an
underlying database table or tables.
It differs from a snapshot-type Recordset object because the dynaset stores only the primary key for each
record, instead of actual data. As a result, a dynaset is updated with changes made to the source data, while
the snapshot is not. Like the table-type Recordset object, a dynaset retrieves the full record only when it's
needed for editing or display purposes.

A snapshot-type Recordset object is a static set of records that you can use to examine data in an
underlying table or tables. In an ODBCDirect database, a snapshot-type Recordset object corresponds to a
static cursor.
Remarks
To create a snapshot-type Recordset object, use the OpenRecordset method on an open database, on
another dynaset- or snapshot-type Recordset object, or on a QueryDef object.
10.How would you define and use a Boolean in VB? (Integer in VB3 Boolean in VB6+)
Dim [Private][Public] x as Boolean
Default is false
11. What is the difference between Dim nCount as Integer vs Dim nCount% and when would you use each?
No difference
12.What is the difference between <F8> and <Shift-F8> when debugging?
F8- will take u through all the executable statements
<SHIFT> f8 – will skip the calls to subroutines
13.What is the statement to extract 4 characters from the middle of a string?
Mid(string, start [, length] )
14. What is the error message that you would get if you try to assign "Null" to an integer variable?
Invalid use if null
16. What is "Option Explicit"?
It mandates the programmer to declare the variables before using
17. What other options are there is VB?
Option private
Option compare text,binary
Option base 0,1

18. What is the difference between Single and Double in VB?


Single: can hold numbers that r approximations Accuracy up to 7 digits only
Double : can hold up to 300 digits with 16 plcess of accuracy
19. How do you clear the current selected item from a drop down combo box?
Combo1.Remove Item(Combo1.ListIndex)

22.What is the difference between early binding and late binding?

Early-Bound Declarations
Early binding allows you to declare an object variable as a programmatic identifier, or
class name, rather than as an Object or a Variant data type. The programmatic identifier
of an application is stored in the Windows registry as a subkey below the
\HKEY_CLASSES_ROOT subtree. For example, the programmatic identifier for Access
is "Access.Application"; for Excel it is "Excel.Application."
When you are using early binding, you can initialize the object variable by using the
CreateObject or GetObject function or by using the New keyword if the application
supports it. All Office 2000 applications can be initialized by using the New keyword.
Because the Outlook 2000 programming environment for Outlook items supports only
scripting, you can't use early binding declarations of any sort in its VBScript
programming environment; however, you can use early binding in VBA code in a local
Outlook VBA project or COM add-in, or in Automation code that works with Outlook
from another host application.
Early binding is the friendly name for what C programmers call virtual function table
binding, or vtable binding. In order to use early binding, the host application must
establish a reference to a type library (.tlb) or an object library (.olb), or an .exe, .dll, or
.ocx file that contains type information about the objects, methods, properties, and events
of the application or service you want to automate.
In the following code fragment, an Application variable is declared by using the
programmatic identifier for Word (Word.Application) and a new instance of Word is
created by using the Set statement with the New keyword:
Dim wdApp As Word.Application
Set wdApp = New Word.Application
If the code following these lines doesn't set the Application object's Visible property to
True, the new instance of Word will be hidden. All Office applications are hidden by
default when they are automated from another application.
Use early binding whenever possible. Early binding has the following advantages:
Syntax checking When you use early binding, VBA checks the syntax of your
statements against the syntax stored in the object library during compilation rather than
checking it at run time, so that you can catch and address errors at design time. For
example, VBA can determine if you are using valid properties or methods of an object,
and if you are passing valid arguments to those properties and methods.
Support for statement-building tools When you use early binding, the Visual Basic
Editor supports features that make writing code much easier and less prone to errors, such
as automatic listing of an object's properties and methods, and pop-up tips for named
arguments.
Support for built-in constants When you use early binding, your code can refer to the
built-in constants for method arguments and property settings because this information is
available from the type library at design time. If you use late binding, you must define
these constants in your code by looking up the values in the application's documentation.
Better performance Performance is significantly faster with early binding than with
late binding.

Late-Bound Declarations
Late binding allows you to declare a variable as an Object or a Variant data type. The
variable is initialized by calling the GetObject or CreateObject function and specifying
the application's programmatic identifier. For example, in the following code fragment,
an Object variable is declared and then set to an instance of Access by using the
CreateObject function:
Dim objApp As Object
Set objApp = CreateObject("Access.Application")
Late binding is the friendly name for what C programmers used to call IDispatch binding,
and was the first method of binding implemented in applications that can control other
applications through Automation. For this reason, you can use late binding to maintain
backward compatibility with older applications. However, late binding uses a lot of
overhead; it is faster than dynamic data exchange (DDE), but slower than early binding.
Tip DDE is a protocol that was established before OLE for exchanging data between
Windows applications. There is no need to use DDE to exchange data between Office
applications because of their support for Automation. However, you may have to use
DDE from some other application that doesn't support Automation code in order to work
with data from an Office application. For more information about using DDE, search the
Visual Basic Reference Help for the Office application you want to work with.
The CreateObject function must also be used to work with objects from any Automation
component from script. This is because scripting has no method of establishing references
to type libraries to support early binding.

23 .Difference between ByRef and ByVal?


Only a copy of a variable is passed when an argument is passed by value. If the
procedure changes the value, the change affects only the copy and not the variable itself.
Use the ByVal keyword to indicate an argument passed by value.
For example:
Sub PostAccounts(ByVal intAcctNum as Integer)
.
. ' Place statements here.
.
End Sub

Passing Arguments By Reference


Passing arguments by reference gives the procedure access to the actual variable contents
in its memory address location. As a result, the variable's value can be permanently
changed by the procedure to which it is passed. Passing by reference is the default in
Visual Basic.
If you specify a data type for an argument passed by reference, you must pass a value of
that type for the argument. You can work around this by passing an expression, rather
than a data type, for an argument. Visual Basic evaluates an expression and passes it as
the required type if it can.
The simplest way to turn a variable into an expression is to enclose it in parentheses. For
example, to pass a variable declared as an integer to a procedure expecting a string as an
argument, you would do the following:
Sub CallingProcedure()
Dim intX As Integer
intX = 12 * 3
Foo(intX)
End Sub

Sub Foo(Bar As String)


MsgBox Bar 'The value of Bar is the string "36".
End Sub

Using Optional Arguments


You can specify arguments to a procedure as optional by placing the Optional keyword in
the argument list. If you specify an optional argument, all subsequent arguments in the
argument list must also be optional and declared with the Optional keyword. The two
pieces of sample code below assume there is a form with a command button and list box.
For example, this code provides all optional arguments:
Dim strName As String
Dim strAddress As String

Sub ListText(Optional x As String, Optional y _


As String)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname"
strAddress = 12345 ' Both arguments are provided.
Call ListText(strName, strAddress)
End Sub
This code, however, does not provide all optional arguments:
Dim strName As String
Dim varAddress As Variant

Sub ListText(x As String, Optional y As Variant)


List1.AddItem x
If Not IsMissing(y) Then
List1.AddItem y
End If
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName)
End Sub
In the case where an optional argument is not provided, the argument is actually assigned
as a variant with the value of Empty. The example above shows how to test for missing
optional arguments using the IsMissing function.

Providing a Default for an Optional Argument


It's also possible to specify a default value for an optional argument. The following
example returns a default value if the optional argument isn't passed to the function
procedure:
Sub ListText(x As String, Optional y As _
Integer = 12345)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName) ' Adds "yourname" and
' "12345".
End Sub

Using an Indefinite Number of Arguments


Generally, the number of arguments in the procedure call must be the same as in the
procedure specification. Using the ParamArray keyword allows you to specify that a
procedure will accept an arbitrary number of arguments. This allows you to write
functions like Sum:
Dim x As Integer
Dim y As Integer
Dim intSum As Integer

Sub Sum(ParamArray intNums())


For Each x In intNums
y = y + x
Next x
intSum = y
End Sub

Private Sub Command1_Click()


Sum 1, 3, 5, 7, 8
List1.AddItem intSum
End Sub

Creating Simpler Statements with Named Arguments


For many built-in functions, statements, and methods, Visual Basic provides the option of
using named arguments as a shortcut for typing argument values. With named arguments,
you can provide any or all of the arguments, in any order, by assigning a value to the
named argument. You do this by typing the argument name plus a colon followed by an
equal sign and the value ( MyArgument:= "SomeValue") and placing that assignment in
any sequence delimited by commas. Notice that the arguments in the following example
are in the reverse order of the expected arguments:
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"
End Sub
This is especially useful if your procedures have several optional arguments that you do
not always need to specify.

Determining Support for Named Arguments


To determine which functions, statements, and methods support named arguments, use
the AutoQuickInfo feature in the Code window, check the Object Browser, or see the
Language Reference. Consider the following when working with named arguments:
• Named arguments are not supported by methods on objects in the Visual Basic (VB) object library.
They are supported by all language keywords in the Visual Basic for applications (VBA) object
library.

• In syntax, named arguments are shown as bold and italic. All other arguments are shown in italic
only.

Important You cannot use named arguments to avoid entering required arguments. You
can omit only the optional arguments. For Visual Basic (VB) and Visual Basic for
applications (VBA) object libraries, the Object Browser encloses optional arguments with
square brackets [ ].
For More Information See "ByVal," "ByRef," "Optional," and "ParamArray" in the
Language Reference

22. How does VB Pass arguments to a function by default?


By Ref
23. Can a subroutine pass back values? How?
Yes By passing the values BYREF

24. What does Addressof operator do?

Using the AddressOf Keyword


Any code you write to call a function pointer from Visual Basic must be placed in a
standard .BAS module — you can't put the code in a class module or attach it to a form.
When you call a declared function using the AddressOf keyword, you should be aware of
the following conditions:
• AddressOf can only be used immediately preceding an argument in an argument list; that
argument can be the name of a user-defined sub, function, or property.

• The sub, function, or property you call with AddressOf must be in the same project as the related
declarations and procedures.

• You can only use AddressOf with user-defined subs, functions, or properties — you cannot use it
with external functions declared with the Declare statement, or with functions referenced from
type libraries.

• You can pass a function pointer to an argument that is typed As Any or As Long in a declared Sub,
Function, or user-defined type definition.

Note You can create your own call-back function prototypes in DLLs compiled with
Visual C++ (or similar tools). To work with AddressOf, your prototype must use the
__stdcall calling convention. The default calling convention (_cdecl) will not work with
AddressOf

25. What is the difference between a Sub and a Function?


Sub won’t return values
Fuction return values

26. How will you retain the values of existing elements in a dynamic array when you want to alter the array
size?
Redim with preserve keyword

27. How will you define a function to accept variable number of arguments ?
USING PARAMARRAY
28. How will you define a function to accept optional arguments?
Using optional key word
29. How does the following statements work? On Error Goto Err_Handler
control switches to err handler
30. How does the following statements work? On Error Resume Next
control switches to next executable statement
31 .How does the following statements work? On Error Goto 0
---control switches to same statement again
32 .What will happen if you issue a Resume statement after handling an error?
control switches to same statement again

34. Sequence of events when a form is loaded in VB?


Load .Active, Paint

36.Difference between Modal and Modaless forms?


Visual Basic Concepts
How Modal and Modeless Forms Behave
Out of Process

As mentioned in "Showing Forms from the CoffeeManager Class," modal and modeless
forms displayed by an out-of-process component have a different relationship to a client
application’s forms than they would if displayed by an in-process component. Running
CoffeeWatch will demonstrate this.
Note This topic is part of a series that walks you through creating a sample ActiveX
EXE. It begins with the topic Creating an ActiveX EXE Component.
To demonstrate modal and modeless form behavior with the out-of-process Coffee
component
1. Press F5 to run the CoffeeWatch test program.

2. Click Show Modal Form to display a modal form from the Coffee component.

Depending on your system configuration, the order programs were started, and so
on, the modal form may come up in front of CoffeeWatch — or you may see
something like this:
3. TestForm is not really modal with respect to the CoffeeWatch form. To see this, click anywhere on
the CoffeeWatch form. The Component Request Pending dialog box appears, as shown here:

The dialog box appears because CoffeeWatch is waiting on its call to


CoffeeMonitor.ShowForm, which is waiting on the modal TestForm. However, if
TestForm were truly modal with respect to Form1, clicking on Form1 would
generate a system sound indicating that Form1 was disabled.
4. Click Switch To, to bring TestForm to the front.

Note Depending on your system configuration and the order in which programs
are loaded, the copy of Visual Basic in which Coffee is running may come to the
front along with TestForm, obscuring CoffeeWatch.
5. Click on CoffeeWatch again, to bring it to the front and display the Component Request
Pending dialog box again.

Note If you can’t see CoffeeWatch (the form, not the project), use the task bar
(or press ALT+TAB) to bring it to the front.
In the strict sense of the word, TestForm is modal to CoffeeWatch. That is, you
can’t do anything with CoffeeWatch until TestForm is dismissed. However,
because the two forms are in different processes, CoffeeWatch can appear on top
of TestForm.
6. Click Switch To, to bring TestForm to the front, and then click TestForm’s close box to dismiss
the modal form.

7. Click Show Modeless Form to show TestForm as a modeless form.

TestForm behaves like a modeless form that’s not owned by CoffeeWatch. That is,
it doesn’t stay on top of CoffeeWatch. You can verify this by clicking on each of
the two forms, to bring them alternately to the front.
Important Because TestForm is in a different process from CoffeeWatch, you
cannot make CoffeeWatch the owner of TestForm as you would if the forms were
in the same process — that is, by passing a reference to CoffeeWatch in the
OwnerForm argument of TestForm. For details see "Displaying Forms from Code
Components," in Chapter 8, "Building Code Components."For details see
"Displaying Forms from Code Components," in "Building Code Components."
8. DO NOT dismiss the modeless TestForm. Instead, close CoffeeWatch by clicking its close box.

TestForm doesn’t close. (It may be hidden behind the instance of Visual Basic
containing the CoffeeWatch project — use the task bar or ALT+TAB to bring it to
the front.)
This illustrates two important points: First, a form displayed by an out-of-process
component is not dependent on the client application. Nor is its lifetime limited by
the client’s lifetime.
Second, a loaded form can keep an out-of-process component’s executable from
unloading. For details, see "Starting and Ending a Component" in Chapter 6,
"General Principles of Component Design."For details, see "Starting and Ending a
Component" in "General Principles of Component Design."
In its Terminate event, CoffeeMonitor should unload any forms it has shown.
9. Dismiss TestForm by clicking its close box. The Coffee component remains in run mode. To
return Coffee to design mode, click the End button, or select End from the Run menu.

Once you put an ActiveX EXE project in run mode, it remains in run mode. This
is convenient for testing, but it’s different from the behavior of the made .exe. The
executable for an out-of-process component unloads when the last client releases
its last reference to an object provided by the component, as discussed in "Starting
and Ending a Component."
Note The only way to test the shutdown behavior of an out-of-process
component is to test with the made executable.
The lesson to take away from all this is that out-of-process code components are
generally not the best way to show forms.

Step by Step
This topic is part of a series that walks you through creating a sample ActiveX EXE.
To See
Go to the next step Providing an Asynchronous Notification Event
Start from the beginning Creating an ActiveX EXE Component

Send feedback to MSDN. Look here for MSDN Online resources.

37. What are the different cursor types that can we create using ADO Recordset?
Difference between these cursor types?
Visual Basic Concepts

ADO, DAO and RDO in Visual Basic

In Visual Basic, three data access interfaces are available to you: ActiveX Data Objects
(ADO), Remote Data Objects (RDO), and Data Access Objects (DAO). A data access
interface is an object model that represents various facets of accessing data. Using Visual
Basic, you can programmatically control the connection, statement builders, and returned
data for use in any application.
Why are there three data access interfaces in Visual Basic? Data access technology is
constantly evolving, and each of the three interfaces represent a different state of the art.
The latest is ADO, which features a simpler — yet more flexible — object model than
either RDO or DAO. For new projects, you should use ADO as your data access
interface.

Why Use ADO?


ADO is designed as an easy-to-use application level interface to Microsoft's newest and
most powerful data access paradigm, OLE DB. OLE DB provides high-performance
access to any data source, including relational and non-relational databases, email and file
systems, text and graphics, custom business objects, and more. ADO is implemented for
minimal network traffic in key Internet scenarios, and a minimal number of layers
between the front-end and data source — all to provide a lightweight, high-performance
interface. ADO is called using a familiar metaphor — the OLE Automation interface.
And ADO uses conventions and features similar to DAO and RDO, with simplified
semantics that make it easy to learn.
For a brief overview, see OLE DB Providers.
For detailed information about ADO, see Getting Started with ADO.

DAO and RDO


For backward compatibility, Visual Basic continues to support DAO and RDO for
existing projects.
For More Information For more information on RDO programming, see Using
Remote Data Objects and the RemoteData Control. For information on DAO
programming, see Using Data Access Objects with Remote Databases. Complete DAO
reference can also be found at Microsoft DAO 3.6.

Upgrading from RDO to ADO


Consider upgrading if you decide ADO offers benefits your RDO-based application can
use. See ADO Compared with RDO and DAO for a discussion of the differences among
the platforms and for guidance on changing an RDO-based project to an ADO project.
See Converting from RDO 2.0 to ADO 2.0 for upgrade guidance.

Send feedback to MSDN. Look here for MSDN Online resources.

ADO Cursor Library

The ActiveX Data Objects (ADO) cursor provider, part of the Remote Data Service
(RDS) technology, provides several types of cursors as shown in the following table.
Cursor type Constant
Forward-only cursor adOpenForwardOnly
Keyset-driven cursor adOpenKeyset
Dynamic cursor adOpenDynamic
Static cursor adOpenStatic

You can control how the data source and the chosen ADO cursor library manage
concurrency with the locking options in the following table.
Locking type Constant
Pessimistic concurrency. adLockPessimistic
Optimistic concurrency using row values. adLockOptimistic
Read-only. Changes are not permitted. adLockReadOnly
All updates are deferred until the batch update is finished. To adLockBatchOptimistic
do batch updating, you should select either a keyset or static
cursor.

For More Information For more information on ADO cursor options, search online for
"CursorType Property" in MSDN Library Visual Studio 6.0. For more information on
Remote Data Service (RDS) and how it provides cursor support with ActiveX Data
Objects, search online for "Remote Data Service Developer's Guide" and "Understanding
Remote Data Service Applications" in MSDN Library Visual Studio 6.0. For more
information on using locks to handle multiuser concurrency situations, see Managing
Concurrency with Cursor Locks in this chapter.

Send feedback to MSDN. Look here for MSDN Online resources.

39. What is the difference between a ActiveX DLL and a ActiveX EXE?
ActivexDLL is executes in in process
ActivexExe executes in outprocess

40. What are the types of Instancing property that can be set for a Class in a ActiveX DLL and ActiveX
EXE?
Visual Basic Concepts

Instancing for Classes Provided by


ActiveX Components

The value of the Instancing property determines whether your class is private — that is,
for use only within your component — or available for other applications to use.
As its name suggests, the Instancing property also determines how other applications
create instances of the class. The property values have the following meanings.
• Private means that other applications aren’t allowed access to type library information about the
class, and cannot create instances of it. Private objects are only for use within your component.

• PublicNotCreatable means that other applications can use objects of this class only if your
component creates the objects first. Other applications cannot use the CreateObject function or the
New operator to create objects from the class.

• MultiUse allows other applications to create objects from the class. One instance of your
component can provide any number of objects created in this fashion.

An out-of-process component can supply multiple objects to multiple clients; an


in-process component can supply multiple objects to the client and to any other
components in its process.
• GlobalMultiUse is like MultiUse, with one addition: properties and methods of the class can be
invoked as if they were simply global functions. It’s not necessary to explicitly create an instance
of the class first, because one will automatically be created.

• SingleUse allows other applications to create objects from the class, but every object of this class
that a client creates starts a new instance of your component. Not allowed in ActiveX DLL
projects.
• GlobalSingleUse is like SingleUse, except that properties and methods of the class can be invoked
as if they were simply global functions. Not allowed in ActiveX DLL projects.

Class Modules and Project Types


The value of the Instancing property is restricted in certain project types. Allowed values
are shown in the following table:
Instancing Value ActiveX EXE ActiveX DLL ActiveX Control
Private Yes Yes Yes
PublicNotCreatable Yes Yes Yes
MultiUse Yes Yes
GlobalMultiUse Yes Yes
SingleUse Yes
GlobalSingleUse Yes

Dependent Objects (PublicNotCreatable)


The value of the Instancing property determines the part an object plays in your
component’s object model, as discussed in "Organizing Objects: The Object Model."
If the Instancing property of a class is PublicNotCreatable, objects of that class are called
dependent objects. Dependent objects are typically parts of more complex objects.
For example, you might allow a client application to create multiple Library objects, but
you might want Book objects to exist only as parts of a Library. You can make the Book
class PublicNotCreatable, and let the user add new books to a Library object by giving
the Library class a Books collection with an Add method that creates new books only
within the collection.
Your component can support as many dependent objects as necessary. You can write code
in the Add method of a collection class to limit the number of objects in the collection, or
you can allow the number to be limited by available memory.
For More Information Dependent objects are discussed in detail in "Dependent
Objects," later in this chapter.

Externally Creatable Objects


All values of the Instancing property besides PublicNotCreatable and Private define
externally creatable objects — that is, objects that clients can create using the New
operator or the CreateObject function.

MultiUse vs. SingleUse


In ActiveX DLLs, Instancing for an externally creatable class will most commonly be
MultiUse. This setting allows an in-process component to supply any number of
instances of the class to the client executable, and to any other in-process component.
For ActiveX EXEs, the Instancing values SingleUse and MultiUse define very different
behaviors for a class. MultiUse makes the most efficient use of memory, because it
allows one instance of your component to provide multiple objects to multiple client
applications without duplication of resources or global data.
For example, suppose the SmallMechanicals component provides a Widget class, and the
Instancing property of the class is set to MultiUse. If one client application creates two
Widget objects, or if two client applications each create a Widget object, all the Widgets
will be supplied from one instance of your component.
If the Instancing property of the Widget class is set to SingleUse, the result of both
scenarios above is that a separate copy of your component will be loaded into memory
for each Widget created. The uses and limitations of this behavior are discussed in
Chapter 8, "Building Code Components," and in Appendix A, "ActiveX Component
Standards and Guidelines."The uses and limitations of this behavior are discussed in
"Building Code Components," and in "ActiveX Component Standards and Guidelines."
MultiUse and Multithreading
If your component is an ActiveX EXE marked for unattended execution (that is, it has no
user interaction whatever), and the Instancing property of the Widget class is set to
MultiUse, the result of both scenarios above is that two Widget objects are created in
same copy of SmallMechanicals, each on its own thread of execution.
Apartment Model threading is used, meaning that each thread is like an apartment, and
objects in different apartments are unaware of each other’s existence. This is
accomplished by giving each Widget its own copy of the SmallMechanicals component’s
global data.
For More Information The use of multithreading or SingleUse instancing to avoid
blocked execution is discussed in Chapter 8, "Building Code Components."The use of
multithreading or SingleUse instancing to avoid blocked execution is discussed in
"Building Code Components."

Global Objects
Frequently it’s useful to have utility functions that users of your component can employ
without first creating an instance of one of your objects. In out-of-process components,
such functions are frequently implemented as properties or methods of the Application
object.
If the Instancing property for a class is marked GlobalMultiUse or GlobalSingleUse, then
properties and methods of the class can be invoked without explicitly creating an instance
of the object.
For example, suppose you want your SmallMechanicals component to provide a
GlobalUtility object whose methods are general-purpose functions. You can add a class
module to the SmallMechanicals project, set the Name property to GlobalUtility, and set
the Instancing property to GlobalMultiUse.
Now you can add properties and methods to the class module. For example, you might
implement a ReversePolarity method and a read-only WidgetCount property:
Public Sub ReversePolarity()
' (Code to reverse polarity on all Widgets.)
End Sub
In the client application, the ReversePolarity method can be invoked without first
creating a GlobalUtility object:
Private Sub Command1_Click()
' No object variable is required.
ReversePolarity
End Sub
Note The properties and methods of a GlobalMultiUse object are not part of the global
name space of the component that provides the object. For example, within a project that
contains the GlobalUtility class, you must explicitly create an instance of GlobalUtility in
order to use the object's properties and methods. Other limitations of global objects are
listed in "Global Objects and Code Libraries," in Chapter 8, "Building Code
Components."Other limitations of global objects are listed in "Global Objects and Code
Libraries," in "Building Code Components."
Be careful when choosing names for the properties and methods of global objects. Using
common or obvious names may result in name collisions with other components. Name
conflicts must be resolved by qualifying the property or method with the type library
name:
Private Sub Command1_Click()
SmallMechanicals.ReversePolarity
Esalen.ReversePolarity
End Sub
Important The "global" in global objects refers to the fact that all of the object’s
properties and methods are available in the global name space of your project. It does not
mean that one object is automatically shared by all clients. Each client that uses your
component gets its own global object.
For More Information "Providing Named Constants for Your Component," later in this
chapter, discusses the use of global objects to provide string constants and non-integer
constants. Code components are discussed in depth in Chapter 8, "Building Code
Components."Code components are discussed in depth in "Building Code Components."

Send feedback to MSDN. Look here for MSDN Online resources.

41. What are the different levels of compatibilty that can be set for a ActiveX component in VB and what
do they imply?
Visual Basic Concepts

Levels of Binary Version Compatibility


Visual Basic defines three levels of version compatibility for the interfaces you describe
in your class modules.
• Version identical means that the interfaces are all the same, so the new version of the type library
is exactly the same as the old one. The code inside methods or Property procedures may have been
changed or enhanced, but this is transparent to client applications.

• Version compatible means that objects and/or methods have been added to the type library, but no
changes were made to existing properties or methods. Both old and new client applications can
use the component.

• Version incompatible means that at least one property or method that existed in the old type library
has been changed or removed. Existing client applications that have references to the component
cannot use the new version.

Version-Identical Interfaces
Once your component has been distributed as part of an application, there are several
situations that might cause you to release an update. You might want to optimize the
performance of a method that had turned out to be a bottleneck for users. You might also
need to change the internal implementation of an object’s method to reflect changes in the
business rule on which the method was based.
You can change the code in existing Property procedures or methods, and still have a
version-identical interface, as long as you do not change the names or data types of their
parameters, the order of the parameters, the name of the property or method, or the data
type of the return value.
When you create the executable for a version-identical upgrade, you can use the same file
name for the executable. Visual Basic uses the same version number for the type library.
Important When you release a new version of your component with a version-identical
or version-compatible interface, and retain the same file name for the executable, you
should always use the Make tab of the Project Properties dialog box to increment the file
version number. This ensures that the setup programs for applications that use your
component will replace old versions during setup.

Version-Compatible Interfaces
When you enhance your component by adding new classes, or new properties and
methods to existing classes, you can continue to use the same name for your executable.
As long as you make no changes to existing properties and methods, Visual Basic updates
the version number of the type library but keeps it compatible with the old version
number.
Client applications that are built using the new version of your component will compile
with the new version number, and can make use of all the new features. They cannot be
used with earlier versions of your component, however, because type library versions are
only upward-compatible.
As with version-identical releases, remember to increment the file version number of the
executable.

Version-Incompatible Interfaces
Sometimes design decisions made in an earlier version of a component fail to anticipate
future needs. If you want the code in the component to be useful in new development
projects, you have to change the interface.
For example, the CupsPerAnnum parameter of the Coffee method might be implemented
as an Integer in the first version of a component. It may become apparent, after the
component has been in use for some time, that some clients need to pass a larger value
than can be contained in an Integer.
Changing the declaration of a method is only one of several actions that will cause Visual
Basic to make the version number of the type library incompatible, rendering the new
version unusable with client applications compiled with earlier versions. The following
changes will cause a version incompatibility:
• Changing the Project Name field on the General tab of the Project Properties dialog box.

• Changing the Name property of any class module whose Public property is True (controls), or
whose Instancing property is not Private (class modules).

• Deleting a public class module, or setting its Instancing property to Private.

• Deleting a public variable, procedure, or Property procedure from a public class module or
control, or changing it to Private or Friend.

• Changing the name or data type of a public variable, procedure, or Property procedure in a public
class module or control.

• Changing the names, data types, or order of the parameters of a public procedure or Property
procedure in a public class module or control.

• Changing the Procedure ID (DispID) or other parameters in the Procedure Attributes dialog box.

Time to Take Stock


When you’ve identified a necessary change that will cause your component to be
incompatible with earlier versions, it’s a good idea to take the time to evaluate the entire
set of interfaces, before plunging ahead and creating an incompatible version of your
component.
Consider Multiple Interfaces
Remember that there are alternatives to using Version Compatibility. Consider enhancing
your component by adding new interfaces with the Implements statement, as described in
"Providing Polymorphism by Implementing Interfaces," in Chapter 6, "General Principles
of Component Design."Consider enhancing your component by adding new interfaces
with the Implements statement, as described in "Providing Polymorphism by
Implementing Interfaces" in "General Principles of Component Design."
Multiple interfaces, a key feature of the Component Object Model (COM) — on which
the ActiveX specification is based — provide a more flexible way to enhance software
components. They allow you to evolve your systems over time, without breaking existing
components.
You don’t have to tackle the daunting task factoring your existing class module interfaces
into small interfaces more suitable for use with Implements — one of the benefits of
using multiple interfaces is that you can start small, adding new interfaces to the system
only where new functionality is required.

Going Ahead with Incompatibility


If you decide to go ahead with an incompatible version, you can minimize future
problems for the users of your component by concentrating in one release all the changes
you can anticipate that might break compatibility again if they have to be made in later
releases.
In planning for an incompatible change, treat the project as a fresh start. Devote as much
care to planning as you would if you were creating a brand new component.
Creating an incompatible version requires three steps: changing the project name,
changing the file name, and compiling with No Compatibility selected.
Changing the Project Name
The key change you must make, when you need to distribute an incompatible version of
your component, is the project name. The project name, which is set on the General tab of
the Project Properties dialog box, is the first part of the programmatic ID of each class
your component provides.
For example, the SmallMechanicals component might provide a Widgets class. A client
application would create a variable to contain a reference to a Widget object as follows:
Private wdgDriver As SmallMechanicals.Widget
The programmatic ID is the combination of project name and class name, and it must be
unique. If you create a new version of this component, you might give it the project name
SmallMechanicals200. Both versions of the Widget object could then be registered in the
same Windows Registry without confusion.
Changing the File Name
You must change the file name of an incompatible component. If you use the old file
name without incrementing the file version number, the incompatible component may not
install on computers where the old file exists. If you increment the file version, the new
file will over-write the old, and applications that used the old version will fail.
Compiling with No Compatibility
Before you compile the incompatible component for the first time, open the Project
Properties dialog box (accessible from the Project menu), select the Component tab, then
select No Compatibility in the Version Compatibility box.
Do not omit this step. Compiling with No Compatibility ensures that the new executable
will not contain any GUIDs (for example, class IDs or interface IDs) that belong to the
previous version. This is necessary for applications that use the original version to
continue working correctly.
Tip After compiling once with No Compatibility, switch to Project Compatibility to
simplify your development tasks.

Alternatives to Version-Incompatible Changes


If you prefer not to make the change to multiple interfaces, as described above, you can
take a similar approach with classes.
That is, you can avoid changes that cause version incompatibility by adding new objects,
properties, and methods, instead of changing existing ones. Existing applications
continue using the old methods and objects, while developers of new applications can use
the new objects.
For example, you might discover that to take advantage of enhancements to your General
Ledger system, you need to add a SubAccount parameter to several business rules in your
FinanceRules component.
If each rule is implemented as a method of the GL object, you could avoid creating an
incompatible version of the component by adding a new object named GL97. This object
would have the same methods as the GL object, but with a SubAccount parameter where
appropriate.
If you need to add new versions of existing methods to an object, you can give the new
methods the same name with a version or sequence number added — for example,
‘Execute2.’
This approach is not as flexible or efficient as implementing multiple interfaces. You may
end up replicating entire classes, and class interfaces may become large and unwieldy —
for example, you might find yourself using a Query class with an Execute method, an
Execute2 method, an Execute3 method, and so on. However, it’s a step in the right
direction.
For More Information "Providing a Reference Point for Binary Version Compatibility"
describes when and how to specify a version of your component as a reference point for
version compatibility. See "Version Compatibility" for a list of topics related to this
feature. Software evolution using multiple interfaces is discussed in "Providing
Polymorphism by Implementing Interfaces," in Chapter 6, "General Principles of
Component Design."Software evolution using multiple interfaces is discussed in
"Providing Polymorphism by Implementing Interfaces," in "General Principles of
Component Design."

Send feedback to MSDN. Look here for MSDN Online resources.

Version Compatibility in ActiveX


Components

A component can be part of another application because it provides Automation


interfaces that the other application can manipulate. Each public class module has a
default interface that includes all the properties and methods you added to the class
module, plus any secondary interfaces implemented using the Implements feature.
Once your component has been used in an application — or, in the case of ActiveX
controls, embedded in a document or on a Web page — you can change its interfaces
only at the risk of breaking the client application.
Suppose, for example, that the Spin method of your Widget object has one argument,
Speed. If you distribute a new version of your component, in which you redefine the Spin
method so that it also requires a Direction argument, you could cause run-time errors in
existing applications.
At the same time, a successful component will inevitably spark requests for
enhancements. You will want to provide new objects, or add new properties and methods
to existing objects. Occasionally you will even want to change the arguments of existing
methods of existing objects.
The following topics describe the Version Compatibility feature of Visual Basic, which is
designed to allow components to be enhanced without causing existing applications to
fail.
• When Should I Use Version Compatibility? Describes the Version Compatibility options and
when to use them. Describes an alternative technique for enhancing software components.

• Maintaining Binary Compatibility Describes the versioning system Visual Basic uses to prevent
compatibility problems.

• Levels of Binary Version Compatibility Describes the degrees of binary compatibility Visual
Basic measures.

• Providing a Reference Point for Binary Version Compatibility Describes when and how to
specify a version of your component as a reference point for version compatibility.
• Using Binary Version Compatibility Describes when and how to use the feature, problems you
may encounter, and messages you may get from Visual Basic.

For More Information See "Polymorphism, Interfaces, Type Libraries, and GUIDs," in
Chapter 6, "General Principles of Component Design" for background information and
concepts.See "Polymorphism, Interfaces, Type Libraries, and GUIDs" in "General
Principles of Component Design" for background information and concepts.

42. What does DoEvents do?


Although Timer events are the best tool for background processing, particularly for very long
tasks, the DoEvents function provides a convenient way to allow a task to be canceled. For example, the
following code shows a "Process" button that changes to a "Cancel" button when it is clicked. Clicking it
again interrupts the task it is performing
(go through MSDN)

43. will you use WithEvents?

Handling an Object's Events

An object that raises events is called an event source. To handle the events raised by an
event source, you can declare a variable of the object's class using the WithEvents
keyword.
This topic continues the Widget object example begun in "Declaring and Raising Events."
To handle the PercentDone event of a Widget, place the following code in the
Declarations section of Form1:
To handle the PercentDone event of a Widget, place the following code in the
Declarations section of Form1:
Option Explicit
Private WithEvents mWidget As Widget
Private mblnCancel As Boolean
The WithEvents keyword specifies that the variable mWidget will be used to handle an
object's events. You specify the kind of object by supplying the name of the class from
which the object will be created.
The variable mWidget is declared in the Declarations section of Form1 because
WithEvents variables must be module-level variables. This is true regardless of the type
of module you place them in.
The variable mblnCancel will be used to cancel the LongTask method.

Limitations on WithEvents Variables


You should be aware of the following limitations on the use of WithEvents variables:
• A WithEvents variable cannot be a generic object variable. That is, you cannot declare it As Object
— you must specify the class name when you declare the variable.

• You cannot declare a WithEvents variable As New. The event source object must be explicitly
created and assigned to the WithEvents variable.

• You cannot declare WithEvents variables in a standard module. You can declare them only in class
modules, form modules, and other modules that define classes.

• You cannot create arrays of WithEvents variables.

Writing Code to Handle an Event


As soon as you declare a variable WithEvents, the variable name appears in the left-hand
drop down of the module's code window. When you select mWidget, the Widget class's
events will appear in the right-hand drop down, as shown in Figure 9.9.
Figure 9.9 An event associated with a WithEvents variable
Selecting an event will display the corresponding event procedure, with the prefix
mWidget_. All the event procedures associated with a WithEvents variable will have the
variable name as a prefix. Add the following code to the mWidget_PercentDone event
procedure.
Private Sub mWidget_PercentDone(ByVal Percent As _
Single, Cancel As Boolean)
lblPercentDone.Caption = CInt(100 * Percent) & "%"
DoEvents
If mblnCancel Then Cancel = True
End Sub
Whenever the PercentDone event is raised, the event procedure displays the percent
complete in a Label control. The DoEvents statement allows the label to repaint, and also
gives the user the opportunity to click the Cancel button. Add the following code for the
Click event of the button whose caption is Cancel.
Private Sub Command2_Click()
mblnCancel = True
End Sub
If the user clicks the Cancel button while LongTask is running, the Command2_Click
event will be executed as soon as the DoEvents statement allows event processing to
occur. The module-level variable mblnCancel is set to True, and the
mWidget_PercentDone event then tests it and sets the ByRef Cancel argument to True.

Connecting a WithEvents Variable to an Object


Form1 is all set up to handle a Widget object's events. All that remains is to find a Widget
somewhere.
When you declare a variable WithEvents at design time, there is no object associated with
it. A WithEvents variable is just like any other object variable. You have to create an
object and assign a reference to the object to the WithEvents variable. Add the following
code to the Form_Load event procedure to create the Widget.
Private Sub Form_Load()
Set mWidget = New Widget
End Sub
When the code above is executed, Visual Basic creates a Widget and connects its events
to the event procedures associated with mWidget. From that point on, whenever the
Widget raises its PercentDone event, the mWidget_PercentDone event procedure will be
executed.
To call the LongTask method, add the following code to the Click event of the button
whose caption is Start Task.
' Start Task button.
Private Sub Command1_Click()
mblnCancel = False
lblPercentDone.Caption = "0%"
lblPercentDone.Refresh

Call mWidget.LongTask(14.4, 0.66)

If Not mblnCancel Then lblPercentDone.Caption = 100


End Sub
Before the LongTask method is called, the label that displays the percent complete must
be initialized, and the module-level Boolean flag for canceling the method must be set to
False.
LongTask is called with a task duration of 14.4 seconds. The PercentDone event is to be
raised once every two-thirds of a second. Each time the event is raised, the
mWidget_PercentDone event procedure will be executed.
When LongTask is done, mblnCancel is tested to see if LongTask ended normally, or if it
stopped because mblnCancel was set to True. The percent complete is updated only for
the former case.

Running the Program


Press F5 to put the project in Run mode. Click the Start Task button. Each time the
PercentDone event is raised, the label is updated with the percentage of the task that's
complete. Click the Cancel button to stop the task. Notice that the appearance of the
Cancel button doesn't change immediately when you click it. The Click event can't
happen until the DoEvents statement allows event processing.
You may find it instructive to run the program with F8, and step through the code a line at
a time. You can clearly see how execution enters LongTask, and then re-enters Form1
briefly each time the PercentDone event is raised.
What would happen if, while execution was back in Form1's code, the LongTask method
was called again? Confusion, chaos, and eventually (if it happened every time the event
was raised) a stack overflow.

Handling Events for a Different Widget


You can cause the variable mWidget to handle events for a different Widget object by
assigning a reference to the new Widget to mWidget. In fact, you can make the code in
Command1 do this every time you click the button, by adding two lines of code:
Set mWidget = New Widget '<- New line.
Call mWidget.LongTask(14.4, 0.66)
Set mWidget = Nothing '<- New line.
The code above creates a new Widget each time the button is pressed. As soon as the
LongTask method completes, the reference to the Widget is released by setting mWidget
to Nothing, and the Widget is destroyed.
A WithEvents variable can only contain one object reference at a time, so if you assign a
different Widget object to mWidget, the previous Widget object's events will no longer be
handled. If mWidget is the only object variable containing a reference to the old Widget,
the object will be destroyed.
Note You can declare as many WithEvents variables as you need, but arrays of
WithEvents variables are not supported.

Terminating Event Handling for a WithEvents Variable


As long as there is a Widget object assigned to the variable mWidget, the event
procedures associated with mWidget will be called whenever the Widget raises an event.
To terminate event handling, you can set mWidget to Nothing, as shown in the following
code fragment.
' Terminate event handling for mWidget.
Set mWidget = Nothing
When a WithEvents variable is set to Nothing, Visual Basic disconnects the object's
events from the event procedures associated with the variable.
Important A WithEvents variable contains an object reference, just like any other
object variable. This object reference counts toward keeping the object alive. When you
are setting all references to an object to Nothing in order to destroy it, don't forget the
variables you declared WithEvents.
For More Information The event procedures associated with WithEvents variables
look a lot like event procedures for controls on forms. "Comparing WithEvents to Control
Events on Forms" discusses the similarities and differences.
44. Which datatypes in VB are capable of accepting Nulls?
Variant
45. Is Visual Basic case sensitive in general?
No
46. Is Visual Basic case sensitive in String Comparison? I.e. "STRINGVAL1" = "stringval1" ?
Yes
10. How do you call a function in a DLL?
Ref Doc
15 .What is the error message that you would get if you try to use a recordset that is not initialized to
anything?

20. What is a datacontrol?


Ref Doc
21.Whats the advantages/disadvantages of using datacontrol vs DAO/ADO/RDO?
Ref Doc
33. Difference between variables defined as public in a standard module (.bas) file and a Class file?
35. Sequence of events when a MDI form open with two child forms is closed?
1. Unload event of Active child form
2. Unload event of remain child forms
3. Unload event of MDI Form
4. Terminate Event of unloaded child forms in the order of their unload
5. Finally Terminate event of MDI Form
6. dataquery To be check

38. What is the difference between COM and DCOM?


PE DOC
41. What is the difference between creating a object using New and CreateObject in Visual Basic?
PE DOC

También podría gustarte