By Tim Patrick
Book Price: $49.99 USD
£30.99 GBP
PDF Price: $39.99
Cover | Table of Contents | Colophon
01 Obtain the original text (or string) from the user.
02 If the user didn't supply any content, then quit now.
03 Prepare a destination for the reversed string, empty for now.
04 Repeat the following until the original string is empty:
05 Copy the last character from the remaining original string.
06 Put that character onto the end of the destination string.
07 Shorten the original string, dropping the last character.
08 [End of repeat section]
09 Show the user the destination string.
MsgBox procedure displays a window with a supplied text message. The statement:MsgBox("The answer is " & 42)' ----- This is a standalone comment, on a line by itself.
Dim counter As Integer ' This is a trailing comment.
MsgBox("The counter starts at " & _ ' INVALID COMMENT HERE!
counter) ' But this one is valid.'). Any text following the comment character is a comment, and is ignored when your code is compiled into a usable application. Any single quote that appears within a literal string is not used as a comment marker.MsgBox("No 'comments' in this text.")REM keyword (as in "REMark"), but most programmers use the single-quote variation instead.brandNewValue = 5
Dim statement that defines brandNewValue, Visual Basic will declare the variable on your behalf, assigning it to the Object data type. Don't let this happen to you! You don't know what kind of trouble you will have if you allow such practices in your code. You will quickly find your code filled with mysterious logic bugs, esoteric data issues, recurrent head lice, and so on.brandNewValue = 5 MsgBox(brandNewVlaue)
Option statements included in the Visual Basic language. There are four such statements:Option Explicit OnDim (or a similar statement) before use. It's possible to replace "On" with "Off" in the statement, but don't do it.Option Strict OnLong data value to a 32-bit Integer variable, Visual Basic will normally convert this data to the smaller size for you, complaining only if the data doesn't fit. This type of conversion—a narrowing conversion—is not always safe since the source data will sometimes fail to fit in the destination. (A widening conversion, as with storing Integer data in a Long, always works, since the destination can always hold the source value.) The Option Strict On statement turns off the automatic processing of narrowing conversions. You will be forced to use explicit conversion functions to perform narrowing conversions. This is good, since it forces you to think about the type of data your variables will hold. You can replace "On" with "Off" in this statement, but if I've warned you once, I've warned you twice: don't even try it.=). You've already seen this operator in use in this chapter. Use it to assign some value to a variable (or constant); whatever appears to the right of the operator gets assigned to the reference type or value type variable on the left. The statement:fiveSquared = 25
25 to the variable fiveSquared.seven = 3 + 4
seven = 7
=) operator. A unary operator appears just to the left of its operand. For instance, the unary negation operator turns a positive number into a negative number:negativeSeven = −7
Operator | Description |
|---|---|
+ | The addition operator adds two numbers together. |
+ | The unary plus operator retains the sign of a numeric value. It's not very useful until you get into operator overloading, something covered in . |
− | The subtraction operator subtracts the second operand from the first. |
− | The unary negation operator reverses the sign of its associated numeric operand. |
* | The multiplication operator multiplies two numeric values together. |
/ | The division operator divides the first numeric operand by the second, returning the quotient including any decimal remainder. |
If statement. It is equivalent to English questions in the form "If such-and-such is true, then do so-and-so." For instance, it can handle "If you have $20, then you can buy me dinner," but not "If a train departs Chicago at 45 miles per hour, when will it run out of coal?"If statements have syntax that spans multiple source code lines:01 If (hadAHammer = True) Then 02 DoHammer(inTheMorning, allOverThisLand) 03 DoHammer(inTheEvening, allOverThisLand) 04 ElseIf (hadAShovel = True) Then 05 DoShovel(inTheNoontime, allOverThisLand) 06 Else 07 TakeNap(allDayLong, onMySofa) 08 End If
If statement lets you define branches in your code based on conditions. It is built from three main components:If (or ElseIf) keyword and the Then keyword is the condition. The sample includes two conditions, on lines 01 and 04. Conditions may be simple or complex, but they must always result in a Boolean True or False value. They can include calls to other functions and multiple logical and comparison operators.If ((PlayersOnTeam(homeTeam) >= 9) And _
(PlayersOnTeam(visitingTeam) >= 9)) Or _
(justPracticing = True) Then
PlayBall( )
Else
StadiumLights(turnOff)
End IfIf keyword. If that conditions fails, you can specify additional conditions following an ElseIf keyword, as on line 04. You may include as many ElseIf clauses as you need. The optional Else condition doesn't let you specify a test expression. Instead, it matches everything not yet caught by the If or ElseIf clauses. Only one Else clause is allowed per If statement.Then keyword is followed by one or more Visual Basic statements that are processed if the associated condition evaluates to True. All statements up to the next ElseFor...Next, For Each...Next, and Do...Loop. Just as conditions allow you to break up the sequential monotony of your code through branches, loops add to the usefulness of your code by letting you repeat a specific block of logic a fixed or variable number of times.For...Next loop uses a numeric counter that increments from a starting value to an ending value, processing the code within the loop once for each incremented value.Dim whichMonth As Integer For whichMonth = 1 To 12 ProcessMonthlyData(whichMonth) Next whichMonth
1 To 12), once for each month. You can specify any starting and ending values you wish; this range can also be specified using variables or functions that return numeric values. Once the starting and ending values are obtained, they are not recalculated each time through the loop, even if a function call is used to obtain one or both limits.' ----- Month(Today) returns the numeric month ' for the current date. For whichMonth = 1 To Month(Today) ProcessMonthlyData(whichMonth) Next whichMonth
1) each time through. You can alter this default by attaching a Step clause to the end of the For statement line:For countDown = 60 To 0 Step −1 ... Next countDown
For whichMonth As Integer = 1 To 12
ProcessMonthlyData(whichMonth)
Next whichMonthFor loop, the For Each...Next loop scans through a set of ordered and related items, from the first item until the last. Arrays and collection objects also work, as does any object that supports the IEnumerable interface (all these topics are covered in ). The syntax is quite similar to the standard For statement:For Each oneRecord In setOfRecords ProcessRecord(oneRecord) Next oneRecord
Sub declaration statement and end with an End Sub statement. All of your subroutine's logic appears in between these two mighty jaws.01 Sub ShowIngredients(ByVal gender As Char) 02 Dim theMessage As String = "Unknown." 03 If (gender = "M"c) Then 04 theMessage = "Snips and snails and puppy dog tails." 05 ElseIf (gender = "F"c) Then 06 theMessage = "Sugar and spice and everything nice." 07 End If 08 MsgBox(theMessage) 09 End Sub
Sub keyword (for subroutine), followed by the name of the procedure, ShowIngredients.gender in the sample) and its data type (Char). The arguments are treated as declared variables within the procedure, as is done with gender on lines 03 and 05.gender will be passed by value, as specified through the ByVal keyword. The related ByRef keyword indicates an argument to be passed by reference. If you don't include either keyword, ByVal is assumed. This passing method impacts whether changes made to the argument within the local procedure are propagated back to the calling code. However, the ability to update the original data is also influenced by whether the data is a GoTo statement lets you jump immediately to some other location within the current procedure. The destination of a jump is always a line label, a named line position in the current procedure. All line labels appear at the start of a logical line, and end with a colon.PromptUser: GetValuesFromUser(numerator, denominator) If (denominator = 0) Then GoTo PromptUser quotient = numerator / denominator
GoTo statement jumps back to the PromptUser label when the code detects invalid data. Processing continues with the line immediately following the PromptUser label. You can't use the same label name twice in the same procedure, although you can reuse label names in different procedures. If you want, include another logic statement on the same line as your label, right after the colon, although your code will be somewhat easier to read if you keep labels on their own lines.LabelAlone:
MsgBox("It's all alone.")
LabelAndCode: MsgBox("Together again.")GoTo statement is one of those elements of Visual Basic that is monitored closely by pesky international software agencies, such as the International Committee to Keep GoTo Always Gone (ICK-GAG). That group also scans computer books looking for derogatory references to its organization name—not that it would find anything like that in this book. But its core issue is that overuse of GoTo statements can lead to spaghetti code, such as the following:Dim importantMessage As String = "Do" GoTo Step2 Step6: importantMessage &= "AG!" GoTo Step7 Step3: importantMessage &= "wit" GoTo Step4 Step2: importantMessage &= "wn " GoTo Step3 Step5: importantMessage &= "CK-G" GoTo Step6 Step4: importantMessage &= "h I" GoTo Step5 Step7: MsgBox(importantMessage)