VBA_U8 - Oakton Community College

advertisement
Using the Select Case Statement
and the MsgBox Function
(Unit 8)
Visual Basic for Applications
Objectives
 In this unit, you will learn how to:
 Perform selection using the Select Case statement
 Use a message box to communicate with the user
 Use the QueryTables collection and QueryTable object
in Excel to retrieve external data
 Use the SQL SELECT statement in Excel, Word, and
Access to select records
 Use the MailMerge object in Word to create labels
Concept Lesson:
More on the Selection Structure
 You might have more than two paths from
which a selection structure must choose
 When a selection structure has several paths
from which to choose, it is usually simpler
and clearer to use the Case form of the
selection structure instead of the nested If
form
 The Case form is sometimes referred to as an
extended selection structure in a procedure
The Select Case Statement
 The Select Case statement begins with the Select
Case clause and ends with the End Select clause
 Between the Select Case and End Select clauses
are the individual Case clauses
 Each Case clause represents a different path that
the selection structure can follow
 The Select Case clause must include a
testexpression
 The testexpression can be any numeric, string, or
Boolean expression
The Select Case Statement
 Each of the individual Case clauses, except the
Case Else, must contain an expressionlist, which
can include one or more numeric, string, or
Boolean expressions
 The data type of the expressions included in the
expressionlists must be compatible with the data type
of the testexpression
 When the Select Case statement is processed, the
value of the testexpression is first compared with the
values listed in expressionlist1
 If a match is found, the instructions for the first Case
clause are processed and then the instruction following
the End Select clause is processed
Syntax and an Example of the
Select Case Statement
Exhibit 8-1: The syntax and an example of the Select Case statement
Using To and Is
in an Expressionlist
 You can use either the keyword To or Is to specify a
range of values in an expressionlist; the values
included in the range can be either numeric or a
string
 When you use the To keyword in a Case clause, the
value preceding the To always must be smaller than
the value following the To
 If you neglect to type the keyword Is in an
expression, the Visual Basic Editor will type it in for
you
Example of Using the To and Is
Keywords in a Select Case Statement
Exhibit 8-3: An example of using the To and Is keywords in a Select
Case statement
The MsgBox Function
 In addition to the MsgBox statement, VBA also has a
MsgBox function
 The MsgBox function allows you to display a dialog
box that contains a message, one or more command
buttons, and an icon
 After displaying the dialog box, both the MsgBox
statement and the MsgBox function wait for the user
to choose one of the command buttons
 Unlike the MsgBox statement, the MsgBox function
returns a value that indicates which button the user
chose
Syntax and Examples of the
MsgBox Statement & the MsgBox Function
Exhibit 8-4: The syntax and examples of the MsgBox statement and
the Msgbox function
The Buttons Argument
 The buttons argument is an optional numeric
expression that represents the sum of values
specifying the number and type of buttons to display
in the dialog box, the icon style to use, and the
identity of the default button
 If you omit the buttons argument, the dialog box
contains an OK button only; it does not contain
an icon
 The buttons argument’s settings are divided into
three groups
 If you do not want to display an icon in the message
box, you do not need to include a number from the
second group in the buttons argument
Valid Settings for the buttons Argument
Exhibit 8-5: The valid settings for the buttons argument
MsgBox Function’s Buttons
Exhibit 8-6: The Msgbox function’s buttons
Values Returned by the
MsgBox Function
If the user selects the
Retry button, the
MsgBox function
returns the integer 4,
represented by the
intrinsic constant
vbRetry
Exhibit 8-7: Some examples of using the Msgbox
function’s return values
Summary
To use the Select Case statement to code the
selection structure:
 Use the syntax shown in Figure 8-1, where the
testexpression and the expressionlists can contain
a numeric, string, or Boolean expression
composed of a combination of variables,
constants, functions, and operators
To specify a range of values in a Case clause’s
expressionlist:
 Use the keyword To in the following syntax:
smallest value in the range TO largest value
in the range
Summary
 Use the keyword Is in the following syntax: Is
relational operator value
To display VBA’s predefined message box, and then
return a value that indicates the button that was
selected in the message box:
 Use the MsgBox function.
Excel Lesson:
Viewing the MthSales Database
and the Sales Worksheet
 The Student Data folder contains the Access
database that is used to record each store’s
monthly sales information
 The database
is named MthSales, and
it is stored in the Tut08\Excel folder
Viewing the MthSales Database
and the Sales Worksheet
 To view the workbook:
1.
2.
Start Microsoft Excel
Open theT8-EX-1 (T8-EX-1.xls) workbook,
which is located in the Tut08\Excel folder in
the Student Data folder on your hard drive. Click
the Enable Macros button, if necessary, then save
the workbook as Monthly Sales. The Monthly Sales
workbook contains one worksheet, named Sales.
Using Microsoft Query
 Microsoft Query is a separate program that
comes with Microsoft Excel, and it is used
to bring data from a database into an
Excel worksheet
 Microsoft Query can retrieve data from the
following database sources: Microsoft SQL,
Microsoft Access, Microsoft Excel, Oracle, SQL
Server, and text file databases
Remarks Using Microsoft Query
 If you import data using the user interface, data from a Web
query or a text query is imported as a QueryTable object,
while all other external data is imported as a ListObject
object.
 If you import data using the object model, data from a Web
query or a text query must be imported as a QueryTable,
while all other external data can be imported as either a
ListObject or a QueryTable.
http://msdn.microsoft.com/en-us/library/office/ff834459.aspx
The QueryTables Collection and
QueryTable Objects
 Each QueryTable object represents a worksheet table built
from data retrieved from an external data source
 You can use the QueryTable object’s CommandText property
to select a different set of records to retrieve from the
database and display in the worksheet
Exhibit 8-9: The QueryTables collection and QueryTable objects
shown in the Excel Object Model
Create a Query Table in VBA
Public Sub CreateQueryTable()
Dim qtbSales As QueryTable
Dim sqlString As String
Dim connString As String
sqlString = "SELECT * FROM 2002Sales ORDER BY Goal DESC"
connString = _
"ODBC;DSN=MS Access Database;DBQ=H:\...\MthSales.mdb"
Set qtbSales = ActiveSheet.QueryTables.Add(Connection:=connString, _
Destination:=Range("a3"), Sql:=sqlString)
qtbSales.Name = "SalesQuery"
qtbSales.Refresh
End Sub
External Data Range Properties
Dialog Box
Exhibit 8-8: The External Data Range Properties dialog box
SQL(Structured Query Language)
 SQL, pronounced like the word “sequel,” stands for
Structured Query Language
 SQL is a set of commands, or statements, that allow
you to access and manipulate the data stored in
many database management systems
 SQL is not case sensitive, but programmers use
capital letters for SQL keywords
The SQL SELECT Statement
 The most commonly used SQL command is the
SELECT statement
 The SELECT keyword allows you to select which
database fields (and records) you want to view
 Separate field's by comma, or use an asterisk (*) to
select all fields
 You can also control the order in which the fields
and records appear
SQL SELECT Examples
 SELECT FirstName, LastName FROM tblStudent;
 SELECT tblStudent.FirstName, tblStudent.LastName FROM tblStudent;
 SELECT LastName FROM tblStudent WHERE City = ‘Des Plaines’;
 SELECT LastName FROM tblStudent WHERE City = ‘Skokie’ OR City= ‘Niles’;
 SELECT LastName FROM tblStudent WHERE City LIKE ‘D*’;
 SELECT LastName FROM tblStudent ORDER BY FirstName , City DESC;
Basic Syntax and Examples of
the SQL SELECT Statement
Exhibit 8-10: The basic syntax and examples of the SQL statement
The SQL SELECT Statement
 The ORDER BY field part of the syntax—referred to as
the ORDER BY clause—allows you to control the
order in which the records appear when displayed
 After assigning a SELECT statement to the
CommandText property, you then must use the
QueryTable object’s Refresh method to update the
query table
 The Refresh method tells Microsoft Excel to connect
to the query table’s data source, execute the query
that appears in the CommandText property, and then
return the appropriate data to the query table
Creating the DisplaySales
Macro Procedure
 The DisplaySales macro should allow anyone to display, in
the Sales worksheet, the sales for either all of the stores on
only a specific store
 It also should calculate the difference between the monthly
sales goals and the actual sales made
Pseudocode for the
DisplaySales Procedure
Exhibit 8-11: The pseudocode for the Display Sales procedure
Word Lesson:
Viewing the Data Source and
the Main Document
 The mail merge feature in Word allows you
to merge a Word document, called the main document, with the
data contained in a
data source
 The data source can be another Word document, an Access
database, an Outlook contact list, an Excel worksheet, or some
other source
 Before creating the procedure, open Nancy’s main document,
which is a Word document stored on your Data Disk
 You will use this document to generate the Willowtown Health Club
labels
The MailMerge Object
 You use the MailMerge object’s Destination
property to control the destination of the
merged documents
The MailMerge Object
 To select the records to be merged with the main
document, you use the syntax
mailMergeObject.DataSource.QueryString = query,
where query is a string that represents a valid SQL
SELECT statement
Exhibit 8-12: The valid settings for the MailMerge object’s
destination property
The SQL SELECT Statement
 Different applications handle the capitalization of SQL
keywords in different ways
 In this book, you will be entering all SQL keywords in
uppercase letters
 The full syntax of the SELECT statement contains
other clauses and options that are beyond the scope
of this book
 To display records in descending order, add the
keyword DESC after field in the ORDER BY clause
 After selecting the appropriate records to merge, you
use the MailMerge object’s Execute method to
perform the mail merge
Pseudocode for the
GenerateLabels Procedure
Exhibit 8-13: The pseudocode for the GenerateLabels procedure
Access Lesson:
Creating the DisplayReport
Procedure
 Professor Martinez’s database is stored in the Student
Data folder on your hard disk
 Begin by opening the database and viewing the
Payments table
 To open the Trip database and view the Payments
table, double-click on Trip and Payments respectively
 The database contains one table named Payments and
one report named PayReport
 The Payments table contains five fields: ID, LastName,
FirstName, Paid, and Updated
Creating the
DisplayReport Procedure
 The Paid field, which stores the total amount
paid by each student, is a Currency field
Pseudocode for the
DisplayReport Procedure
Exhibit 8-14: The pseudocode for the DisplayReport procedure
Download