Additional Questions Arising in MIS
210
Site Developed by Edward Williams
Ongoing assistance from John M. Dennis, a colleague and
Visual Basic(c) expert, in building and maintaining this site, is
gratefully acknowledged.
- Q: How do I insert comments in code?
A: Type a single quote or apostrophe at the beginning of the comment; the
single quote should be preceded and followed by a blank space for
readability. An entire-line comment may begin with an apostrophe or the
keyword "Rem" (short for "remark").
- Q: How do I break one VB
statement across lines?
A: The last character of the line must be an underscore ("_"), and that
underscore must be preceded by at least one blank space. The line cannot
be broken in the middle of a "word" (e.g., an identifier).
- Q: How do I put multiple statements on one line?
A: In general, you don't, or shouldn't; doing so can make code very
difficult to read. However, statements that are very short and closely
related may reasonably be put on the same line. To do so, separate them
with a colon. Example:
sngX = sngX1 : sngY = sngY1 ' copy Cartesian co-ordinates
- Q: What are some good techniques for controlling the movement of the
focus when the user presses the "Tab" key?
A: When the user presses the tab key, the focus goes to the next control
(in TabIndex sequence) capable of receiving the focus (for example, a
Label control cannot receive the focus, but a Text Box control can).
TabIndex sequence numbers are, by default, assigned in the order controls
are added to a Form. Therefore, I recommend placing the controls on the
Form in the general order in which the user will traverse them. For
example, if a Label specifies what the user should type into a matching
Text Box, place the Label control on the Form and then place the matching
Text Box on the form (rather than placing all Labels on the Form,
and then all Text Boxes). Near the end of Form layout, reassign
TabIndex sequence numbers as needed.
- Q: What are some comments on "when to use which data type" in
addition to the text material on pages 166-167?
A: The Byte data type is useful for counters which assume only reasonably
small values (must stay below 256) and cannot possibly be negative (e.g.,
number of salespeople in a small store).
Although the Single type can
assume an enormous range of values, it carries fewer significant digits
than does the Double type. The Double type is occasionally needed for
long engineering or scientific calculations during which round-off errors
gradually accumulate.
- Q: What are the three levels of scope?
A: The narrowest scope is "local" -- variable is accessible to only one
procedure pertinent to one control. The variable vanishes when the
procedure completes execution (unless it is Static -- see Exercise 20
page 189). The next level of scope is "form" -- the variable is
accessible to every procedure in the form. The broadest level of scope is
"global," in which a variable is accessible across the entire
project.
If variables of different scope have identical names, a
procedure will use the variable of narrowest scope accessible to
itself.
General principle: use the narrowest scope that will get the job done (a
variety of information hiding).
Additionally:
If a variable is declared with a "Public" statement
instead of a "Dim" statement, it acquires "global" scope. The "Public"
declaration can be used only at the Form level, not the Procedure
level.
The "Private" statement has replaced the "Dim" statement for
"form" scope of variables declared at the Form level; however, the
"Private" statement, like the "Public" statement, is illegal in
declarations within a Procedure.
For backward compatibility, "Dim" can
be used instead of "Private" at the Form level (bad practice). At the
Procedure level, declarations must begin with "Dim" or "Static".
- Q: What is an additional reason to use symbolic constants?
A: The textbook points out (page 184) that these constants make a program
easier to read and understand. Here is another reason: suppose the tax
rate is 5%, and the literal constant 0.05 is sprinkled through the
procedures in a project. Now the legislature raises the tax rate to 6%.
The maintenance programmer must find all instances of 0.05 and change them
to 0.06 -- OOPS -- one of those 0.05 wasn't really the tax rate, it was
the commission for the referring agent, and now we have two new bugs --
the place where the tax rate wasn't changed, and the place where the
commission rate was changed wrongly. Better: we had the line
Const conTaxRate as Single = 0.05
and we changed it
to:
Const conTaxRate as Single = 0.06
- Q: What is the difference between the operator "+" and "&"?
A: They overlap: "&" can be used to concatenate strings; "+" can be used
to concatenate strings or to add numbers. For clarity, use "+" only to
add numbers.
- Q: What is the distinction between modal and
modeless in the context of describing a form?
A: A modal
form demands that the user devote
attention to it before using any other form or dialog box, by doing
something that causes code to execute either hiding or unloading the form.
A modeless form does not make this demand of the user.
- Q: What is the distinction between a syntax error and a logic
error?
A: A syntax error is a violation of the language Visual Basic
can detect. A logic error is a flaw in translating the user's and
programmer's intentions into Visual Basic; Visual Basic cannot
detect a logic error. Here's an example of a syntax error in
English:
The dog bited the mail carrier. (since "to bite" is a
strong verb)
Here's an example of a logic error:
The mail
carrier bit the dog.
- Q: Page 250 says Visual Basic has 6 logical operators and describes
3. What are the other 3?
A: One is "Xor", meaning eXclusive OR. This
operator is True if exactly one of its operands is True; otherwise,
False.
Another is "Eqv", meaning EQuiValent. This operator is True if
both of its operands are True or if both of its operands are False. If
its operands have different Boolean values, Eqv returns False.
The last
logical operator is "Imp", which stands for IMPlication. Imp returns True
unless its first operand is True and its second operand False, in which
case Imp returns False.
- Q: What is the difference between sentence capitalization and book
capitalization?
A: Sentence capitalization capitalizes only the first
word and any other words always capitalized by fiat (for example, the
names of the months are always capitalized in English). Book
capitalization capitalizes the first word and all "important" words,
except for short articles and prepositions. Examples:
Sentence
capitalization:
This sentence was written in March.
Book
capitalization:
This Title Was Written in April.
- Q: What is the distinction between Load and Show?
A: Load brings
a Form into memory, but does not make it visible. Show makes a Form
visible, performing a preparatory Load if necessary. Unload is the exact
antonym of Load. Hide is the exact antonym of Show.
- Q: We skipped over pages 224-225 of the text about changing the mouse
pointer. Since reference is made there to value 13, there must be many
mouse pointer options. What are the others?
A: There are many; see
the following table. Note that changing the
mouse pointer does not, in and of itself, undertake actions such as
permitting or preventing resizing. Changing the mouse pointer simply
communicates to the user -- no small feat in itself.
- Q: How does the "Switch" statement, which is not in our
text,
work?
A: "Switch" is an alternative to "If" with many "Else" clauses,
or to a "Case" statement. It is less bulky than either, but does not
provide Else functionality. As an example, here's Exercise 5, page 276,
implemented with a Switch statement:
curCharge = Switch(intCode <= 0, 0, _
intCode <= 3, 25, _
intCode <= 6, 20, _
intCode <= 10, 15, _
intCode > 10, 10)
Hence, Switch is "activated" by the first True condition it finds.
- Q: How does the "ElseIf" keyword work?
A: This keyword
works much like "Switch". A skeleton of code would look like:
If condition-1
thencode-block-1
ElseIf condition-2
thencode-block-2
ElseIf condition-3
thencode-block-3
Else
code-block-4
End
If
"ElseIf"
must be written as one word.
The "Else" block may be omitted, but must
be the last block if it appears. The first block of code whose header
condition is True will be executed. At most 1 block of code will be
executed. If the "Else" block is present, exactly 1 block of code will be
executed.
- Q: What is the difference between a function and
a
subprocedure?
A: A function is invoked and returns a value. A
typical function invocation looks like:
return_value = function_name(argument_one, argument_two,
argument_three)
A subprocedure is called. A typical
subprocedure call looks like:
Call subprocedure_name(argument_one,
argument_two, argument_three)or
subprocedure_name
argument_one, argument_two, argument_three
Ucase is a function
which returns the upper-case version of its one argument, the character
string sent to it. RandomNumbers (we wrote it on page 296) is a
subprocedure taking zero arguments.
- Q: What are some additional repetition-of-code
capabilities in
Visual Basic?
A: Visual Basic has 6 looping structures, 3 of which are
covered in Tutorial 5, Lesson A. They are:
- For/Next (pp. 340 ff.), to be used when the analyst knows, on loop
entry, how many times the loop needs to be executed. The loop may be
executed zero or more times.
- Do While/Loop (pp. 344 ff.), to be used when the analyst does not
know, on loop entry, how many times the loop needs to be executed, but
wishes the loop to be executed zero or more times while a condition
remains true.
- Do/Loop Until (pp 344 ff.), to be used when the analyst does not know,
on loop entry, how many times the loop needs to be executed, but wishes
the loop to be executed one or more times while a condition remains
false.
- While/Wend, to be used when the analyst does not know, on loop entry,
how many times the loop needs to be executed, but wishes the loop to be
executed zero or more times while a condition remains true.
This structure is a clone of Do While/Loop.
It is provided for backward
compatibility with earlier versions of Visual Basic(c). I recommend
disdaining its use because (a) plans are to phase it out of the language,
and (b) it cannot be exited "from the side" (see below).
- Do/Loop While, to be used when the analyst does not know, on loop
entry, how many times the loop needs to be executed, but wishes the loop
to be executed one or more times while a condition remains
true.
- Do Until/Loop, to be used when the analyst does not know, on loop
entry, how many times the loop needs to be executed, but wishes the loop
to be executed zero or more times while a condition remains
false
An Exit For statement may be placed inside
a For/Next loop to provide premature exit "from the side" of the loop as
the analyst deems necessary (e.g., if an unforeseen error such as faulty
data or failure of convergence in a mathematical algorithm manifests
itself). The Exit Do statement may be similarly used within the
other looping structures, except for the While/Wend (#4 above).
- Q: What if I want things to be done when a control
loses the focus, instead of when it gains the focus?
A:
Write code describing the things to be done within, not the GotFocus event
procedure, but the LostFocus event procedure.
- Q: What was the specific error and its effect relative to
page 318 (and derivatively page 320) of the textbook?
A: The symbolic
constant conBtns matches the "buttons" argument in the table on
page 314. It must be declared As Integer, not As
String. Indeed, it is defined as the sum of 4 integers, one from
each of the groups shown in the table on page 315.
- Q: What are some properties of control arrays?
A: The
Count property retrieves the number of control array
elements.
The LBound and UBound properties retrieve
the lower and upper bounds, respectively, of indices pertinent to the
array. By default, these indices are consecutive from zero to Count-1,
but that is not required.
In Tutorial 5, lesson B, chkDone.Count = 5,
chkDone.LBound = 0, and chkDone.UBound = 4.
- Q: What is the difference between the functions
Ucase and Ucase$?
A: Ucase returns a type
Variant, presumably to be placed in a string, whereas Ucase$
returns a type String. Consider the lines of code
strMyString =
Ucase(strMyString) versus
strMyString =
Ucase$(strMyString)
The first line returns a Variant which is
automatically converted to a String for assignment to strMyString, whereas
the second returns a String for immediate assignment to strMyString.
Therefore, the second (using the "$") is more efficient and recommended.
- Q: Aside from twips (page 46 of text), what other
coordinate systems are available?
A: There are 8 coordinate system
scales accessible through the ScaleMode property of a Form. They
are:
0 (vbUser) scale defined by the programmer
1 (vbTwips)
twips
2 (vbPoints) points (a point is 1/72nd inch)
3
(vbPixels) pixels (each pixel is one dot of screen resolution)
4
(vbCharacters) 120 twips horizontally, 240 twips vertically
5
(vbInches) physical inch
6 (vbMillimeters) physical millimeter
7
(vbCentimeters) physical centimeter
Pixels are a
device-dependent unit of measurement, whereas twips are a
device-independent unit of measurement.
- Q: How do I make sure that, for example, only digits can
be entered into a text box?
A: A text box has a KeyPress event which
returns an integer KeyAscii specifying which key the user pressed. Every
key the user presses has an ASCII code, integer-valued. For example, the
backspace key has ASCII code 8. A built-in VB function Asc returns the
ASCII code for any character. The following lines of code will ensure
that only numbers are typed:
If (KeyAscii < Asc("0") Or KeyAscii > Asc("9")) And KeyAscii <> 8) Then
KeyAscii = 0 ' setting to zero cancels the user's key press
End if
This code would appear in the KeyPress event of the text box control.
- Q: How do I put a double-quote mark into a character
string, inasmuch as that character is used to delimit a string fore and
aft?
A: Use the "Chr$" function, which is the inverse of the "Asc"
function described in the immediately preceding Q&A. The double-quote
mark has ASCII code integer 34. So, for example, the
line
txtMyTextBox.text = "Test" & Chr$(34) & "String"
will
set the content of txtMyTextBox.text to the eleven-character string
Test"String
- Q: I saw code reading:
lblMyTextBox =
strMyString
It actually seemed to work! How?
A: That line of
code defaults to
lblMyTextBox.Caption =
strMyString
inasmuch as the most frequently used property of a
Text Box control is the Caption property. If the "." and the property
name are omitted thus, the default is to the most commonly used property.
Such omission is a horrible programming practice.
- Q: Isn't there an easier way to ensure that a form appears
centered on the screen than to do the fussing with co-ordinates at the
time of the form's Load event?
A: Yes. In the Properties list for the
form, change the StartUpPosition property from 3 ("Windows Default") to 2
("CenterScreen"). This method works reliably in the default MDI (Multiple
Document Interface). In the SDI (Single Document Interface), the reset
value of the StartUpPosition property will be lost if the user
subsequently moves or resizes the form window in design mode.
- Q: How does the user toggle between MDI (Multiple Document
Interface) and SDI (Single Document Interface)?
A: On the Tools menu,
select Options; then select the Advanced tab. Check the "SDI" check box.
The change will take effect next time Visual Basic is started.
- Q: What are similarities and differences between Image
controls and PictureBox controls?
A: The basic similarity: both
support graphic image presentation. However, Image controls can stretch
(recall our first lesson with the corporate logo); PictureBox controls
can't. Image controls use less memory than do PictureBox controls. Both
can be bound to fields in a database to support DDE (dynamic data
exchange). Graphics can't be drawn (at execution time) on top of an
Image, but they can be drawn on top of a PictureBox. The perhaps most
significant difference: PictureBox, unlike Image, is a container object.
For example, a set of command buttons can be placed physically on a
PictureBox, and become contained in the PictureBox. If, at run
time, the PictureBox Visible property is set to False, the command
buttons, as well as the picture itself, disappear from the user's screen.
- Q: Can controls be created at run time?
A: Certainly!
For example, clicking on a command button can create new command buttons,
each with different click-on actions. A common approach is to create the
initial command button, at design time, as the zero-th element of an array
(set its Index property, by default blank, to 0). Then write code for the
click event as illustrated in this example (download and unzip).