vel11.htm

来自「简单的说明如何使用VB,非常适合初学使用者,而且是用图表来解说的」· HTM 代码 · 共 2,549 行 · 第 1/4 页

HTM
2,549
字号
<HTML><HEAD><TITLE>Visual Basic in 12 Easy Lessons vel11.htm </TITLE><LINK REL="ToC" HREF="index.htm"><LINK REL="Index" HREF="htindex.htm"><LINK REL="Next" HREF="vel12.htm"><LINK REL="Previous" HREF="velp05.htm"></HEAD><BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#800080"><A NAME="I0"></A><H2>Visual Basic in 12 Easy Lessons vel11.htm</H2><P ALIGN=LEFT><A HREF="velp05.htm" TARGET="_self"><IMG SRC="purprev.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="Previous Page"></A><A HREF="index.htm" TARGET="_self"><IMG SRC="purtoc.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="TOC"></A><A HREF="vel12.htm" TARGET="_self"><IMG SRC="purnext.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="Next Page"></A><HR ALIGN=CENTER><P><UL><UL><UL><LI><A HREF="#E68E85" >What You'll Learn</A><LI><A HREF="#E68E86" >Arrays Hold Data</A><LI><A HREF="#E68E87" >The Advantage of Arrays</A><LI><A HREF="#E68E88" >List Boxes: Controls That Work Like Arrays</A><LI><A HREF="#E68E89" >Combo Boxes</A><LI><A HREF="#E68E90" >Homework</A><UL><LI><A HREF="#E69E78" >General Knowledge</A><LI><A HREF="#E69E79" >Write Code That...</A><LI><A HREF="#E69E80" >Extra Credit</A></UL></UL></UL></UL><HR ALIGN=CENTER><A NAME="E66E16"></A><H1 ALIGN=CENTER><CENTER><FONT SIZE=6 COLOR="#FF0000"><B>Lesson 6, Unit 11</B></FONT></CENTER></H1><BR><A NAME="E67E19"></A><H2 ALIGN=CENTER><CENTER><FONT SIZE=6 COLOR="#FF0000"><B>Arrays and Lists</B></FONT></CENTER></H2><BR><BR><A NAME="E68E85"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>What You'll Learn</B></FONT></CENTER></H3><BR><UL><LI>Arrays hold data<BR><BR><LI>The advantage of arrays<BR><BR><LI>List boxes: Controls that work like arrays<BR><BR><LI>Combo boxes<BR><BR></UL><P>Variables and controls hold the data that your Visual Basic programs process. You've now seen the different kinds of variable data types that Visual Basic supports, as well as three of the primary controls used on forms: command buttons, labels, and text boxes.<BR><P>This unit extends the discussion on variables and controls by showing you a new way of managing variable data storage. By storing variables in arrays, you'll be able to process larger amounts of data with less code than you could with the kinds of variables that you've seen so far.<BR><P>After you learn about the concept of arrays and how you access variable arrays, you'll discover three more controls that you can place on forms. These controls, the list box and combo box controls, give you a simple way to display array data on forms.<BR><BR><A NAME="E68E86"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>Arrays Hold Data</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>An array is a table of values in memory. Unlike variables to which you assign different names, multiple variables stored in arrays all have the same name. You'll reference the different data values using a subscript.<BR><P>All the variables that you've worked with so far require a unique variable name. As you define variables, you define both the variable data types and the variable names. Figure 11.1 shows what you have defined once Visual Basic executes the following variable definitions and assignments:<BR><PRE><FONT COLOR="#000080">Dim Age As IntegerDim Limit As LongDim Salary As SingleDim DogName As String' Store data in the variablesAge = 34Limit = 40294Salary = 982343.23 ' A Visual Basic programmer's payDogName = &quot;Ralph&quot;</FONT></PRE><P><B> <A HREF="11vel01.gif">Figure 11.1. Variables appear in several different memory locations.</A></B><BR><P>Although Visual Basic <I>might</I> define and assign the variables back to back in memory, you don't know or even care where Visual Basic stores the variables. With such variable definitions, all you need are four variables of four data types, and each of those variables has a different name.<BR><P>For variables that fulfill a different purpose, such variable definitions are excellent and work well for simple as well as advanced Visual Basic applications. Nevertheless, there will be times when you'll need several variables of the same data type to hold similar data values. For example, a tag agent's application might need to tally a grand total of all license fees for that day's transactions. If there are one hundred transactions, the only way that you know to define one hundred variables is to define and name each of them differently with statements such as these:<BR><PRE><FONT COLOR="#000080">Dim LicFee1, LicFee2, LicFee3, LicFee4 As CurrencyDim LicFee5, LicFee6, LicFee7, LicFee8 As CurrencyDim LicFee9, LicFee10, LicFee11, LicFee12 As Currency' The rest of the variable definitions would follow</FONT></PRE><P>When you need to define variables that hold the same kind of data values, such as this table of 100 tag agent license values, your program gets burdened down with all those variable names. Filling those variables is a problem as well. Will you supply one hundred text box controls on a form? If the clerk at the counter enters each customer's license amount as the customer pays, how can you collect the next license fee in the next variable?<BR><P>Even if you could find a way to fill the one hundred variables with the daily values, how would you get a total of that data? You would have to write multiple addition statements that begin something like this:<BR><PRE><FONT COLOR="#000080">DayTotal = LicFee1 + LicFee2 + LicFee3 + LicFee4DayTotal = DayTotal + LicFee5 + LicFee6 + LicFee7DayTotal = DayTotal + LicFee8 + LicFee9 + LicFee10' Ugh! This could take forever!</FONT></PRE><P>Again, the variables that you've worked with so far have been great for applications that don't need to process several sets of related data. Computers are used for processing sets of data, however. You may recall from the previous lesson that the power of a computer comes mostly from its capability to loop through code at a high rate of speed, processing large amounts of data quickly and without getting bored. Those large amounts of data <I>must</I> be stored in something other than the stand-alone variables that you've seen so far or the programmer would soon get bogged down with writing huge numbers of variable names every time another calculation was needed.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><I>Definition: </I>An <I>array</I> is a list of values.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>Visual Basic supports the use of arrays to eliminate much of the tedium that you would face if every variable had to have a different name. Rather than define single stand-alone variables using several Dim statements, you can define an entire list of variables. This list, called an array, takes on the following attributes:<BR><UL><LI>Each item in the array is called an <I>element</I>.<BR><BR><LI>Every element in the array must be the same data type.<BR><BR><LI>The list has one name and each item in that list is another occurrence of that name.<BR><BR><LI>You'll use a <I>subscript</I> <I>number </I>to uniquely reference individual elements. The subscript number is often just called the array's <I>subscript</I>.<BR><BR><LI>Instead of using Dim, you'll often use the Static statement to define arrays.<BR><BR></UL><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Note: </B>There are two additional ways to declare arrays, using Dim and the Global statement, that you'll learn about in Lesson 8.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>Figure 11.1's variables could not be stored in an array because their data types are different. The tag agent's one hundred license fees, however, would make excellent array candidates because each fee requires the same data type (Currency).<BR><P>You'll use the Static statement for this lesson to define arrays. Static works a lot like Dim except that Static defines arrays rather than single stand-alone variables. Here is the format of Dim:<BR><BR><PRE><FONT COLOR="#000080">Static ArName(subMax) As DataType</FONT></PRE><P>The <I>ArName</I> is the name that you want to call the array. <I>subMax</I> must be a number that describes the total number of array elements you need. The <I>DataType</I> is a data type that matches one of Visual Basic's data types, such as Single and Long.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Warning: </B>As with any kind of variable, you'll have to define arrays with Static before you can use them.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P><FONT COLOR="#FF8000"><B><I>Stop and Type: </I></B></FONT>Here is the simple way that the tag agent might define the 100 license fee variables:<BR><BR><PRE><FONT COLOR="#000080">Dim LicFee(100) As Currency ' Defines 100 elements</FONT></PRE><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>By defining an array of data, you can define multiple occurrences of variable data without having to assign each variable a different name and without having to define each variable separately. The array will have a single name and be stored together, with all of the array values being sequentially back to back, in memory. You'll access each value using a unique subscript.<BR><P><FONT COLOR="#FF8000"><B><I>Output: </I></B></FONT>Figure 11.2 shows how the LicFee appears in memory.<BR><P><B> <A HREF="11vel02.gif">Figure 11.2. Array elements appear back to back and each has a unique subscript </B><B>that begins at 0.</A></B><BR><P><FONT COLOR="#FF8000"><B><I>Analysis: </I></B></FONT>Visual Basic automatically defines an extra array element with the subscript of 0 when you define an array. The Option Base 1 statement that you can put in the (general) procedure of any form's Code window tells Visual Basic to define arrays with a starting subscript of 1. Without Option Base 1, however, when you request 100 elements, Visual Basic throws in the extra zero subscript. Most Visual Basic programmers choose to ignore the zero subscript, however, and if you do, too, you won't be wasting too much memory by ignoring the extra array element. This book will always ignore the zero-based subscript and work with a starting subscript of 1. If you want to ignore the zero subscript, you can do that without coding the Option Base 1 statement.<BR><P>Visual Basic assigns each element in the array a subscript so that your program can distinguish between each value in the array. As with all variables, Visual Basic assigns zero to each array element, and your program will overwrite those initial zeros when the program assigns data to the array.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Warning: </B>Don't ever attempt to reference a subscript that doesn't exist for a particular array. Visual Basic would issue an error message if your program attempted to do something with LicFee(311) or LicFee(-8) because 311 and -8 are out of the range of LicFee's subscripts that range only from 0 to 100.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><BR><A NAME="E68E87"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>The Advantage of Arrays</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>Arrays eliminate much tedious coding. By using the subscript rather than a different variable name, you can use a For loop to step through arrays and access individual items in sequence.<BR><P>Arrays simplify the process of initializing, printing, calculating, and storing data. If, for example, you were to define an array of 20 string variables that will hold customer names like this:<BR><BR><PRE><FONT COLOR="#000080">Dim CustNames(20) As String</FONT></PRE><P>you <I>could</I> initialize each of those 20 strings with 20 InputBox$() function assignments, like this:<BR><PRE><FONT COLOR="#000080">CustName(1) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(2) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(3) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(4) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(5) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(6) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(7) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(8) = InputBox$(&quot;What is the next customer's name?&quot;)CustName(9) = InputBox$(&quot;What is the next customer's name?&quot;)' And so on for all 20 names</FONT></PRE><P>Wouldn't the following For loop be easier, though?<BR><PRE><FONT COLOR="#000080">For Ctr = 1 To 20 CustName(Ctr) = InputBox$(&quot;What is the next customer's name?&quot;)Next Ctr</FONT></PRE><P>The variable, Ctr, steps through the values from 1 to 20, assigning the result of the InputBox$() function for each of those 20 times. The following similar code could display the 20 names in message boxes:<BR><PRE><FONT COLOR="#000080">For Ctr = 1 To 20 MsgBox CustName(Ctr)Next Ctr</FONT></PRE><P>Of course, the constant display of input and message boxes can get tedious, but focus for now on the programming ease that arrays provide over variables that each have different names. Using a For loop for stepping through an array of values makes working with that array a breeze.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Note: </B>Of course, you don't have to step through every array value when you need to work with only a few of them. For example, you could display only the 5th and 19th customer with two back-to-back message boxes like this:<BR>MsgBox CustName(5)<BR>MsgBox CustName(19)<BR>An array gives you another way to reference data than by using a different variable name. Each element, however, is a unique variable known by its array name and subscript. Therefore, you can work with individual array elements as if they were stand-alone variables by accessing their individual subscripts.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P><FONT COLOR="#FF8000"><B><I>Stop and Type: </I></B></FONT>Listing 11.1 contains a calculating section of code from a procedure that finds the average of the license fee transactions. The array named LicFee had already been filled with values earlier in the procedure. Those values may have come from the form, from the user with input boxes, or from a disk file.<BR><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>The array subscripts enable you to access one or more elements from the array. The big advantage that arrays provide is enabling your program to step through the entire array using a For loop's control variable as the subscript.<BR><P><FONT COLOR="#000080"><B>Listing 11.1. Computing an average license fee from an array.</B></FONT><BR><PRE><FONT COLOR="#000080">1: TotalFee = 0.0 ' TotalFee is defined as Currency2: AvgFee = 0.0 ' AvgFee is defined as a Currency3: For Ctr = 1 To 100 ' There are 100 license fees4: TotalFee = TotalFee + LicFee(Ctr)5: Next Ctr6: ' Now that the total is computed, calculate average7: AvgFee = TotalFee / 100.0</FONT></PRE><P><FONT COLOR="#FF8000"><B><I>Analysis: </I></B></FONT>Before studying Listing 11.1, think about how you compute the average of numbers. You first add all the numbers together, then divide by the total number to get an average. That process is exactly what this code does. The For loop in lines 3 through 5 moves the values from 1 to 100 into the variable named Ctr during each loop iteration. Line 4 adds each of the array values, one at a time as controlled by the For loop, to the TotalFee variable.<BR><P>After all one hundred license fees are added together, line 7 then computes the average of the one hundred values. Subsequent code could either display the average in a label or use the value for another calculation.<BR><BR><A NAME="E68E88"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>List Boxes: Controls That Work Like Arrays</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>The list box control works a lot like an active array on your form that the user can scroll through, seeing all the items in the list. Often, programmers initialize list boxes with data from arrays. Unlike most controls, you can't add values to a list box control through the Property window, but must add the values at runtime through code.<BR><P>Figure 11.3 shows the location of the list box control on the Toolbox window. The list box control displays values through which the user can scroll. The list box doesn't display scroll bars if the size of the list box is large enough to display all the values. Remember that list boxes are for displaying data; the user cannot add data directly to a list box.<BR><P><B> <A HREF="11vel03.gif">Figure 11.3. The location of the list box control.</A></B>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?