Visual Basic 6 Black Book phần 2 pps

112 295 0
Visual Basic 6 Black Book phần 2 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Private Sub Command1_Click() Dim NumberTrains End Sub In this case, the variable NumberTrains is a variant, which means it can take any type of data. For example, here we place an integer value into NumberTrains (note that we specify that 5 is an integer by using the percent sign [%] suffix as specified in Table 3.1): Private Sub Command1_Click() Dim NumberTrains NumberTrains = 5% End Sub We could have used other data types as well; here, for example, we place a string into NumberTrains: Private Sub Command1_Click() Dim NumberTrains NumberTrains = "Five" End Sub And here we use a floating point value (! is the suffix for single values): Private Sub Command1_Click() Dim NumberTrains NumberTrains = 5.00! End Sub Be careful of variants, howeverthey waste time because Visual Basic has to translate them into other data types before using them, and they also take up more space than other data types. Converting Between Data Types Visual Basic supports a number of ways of converting from one type of variable to anotherin fact, thats one of the strengths of the language. The possible conversion statements and procedures appear in Table 3.2. Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\088-091.html (2 of 4) [3/14/2001 1:28:36 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Table 3.2 Visual Basic data conversion functions. To Do This Use This ANSI value to string Chr String to lowercase or uppercase Format, LCase, UCase Date to serial number DateSerial, DateValue Decimal number to other bases Hex, Oct Number to string Format, Str One data type to another CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, CVar, CVErr, Fix, Int Date to day, month, weekday, or year Day, Month, Weekday, Year Time to hour, minute, or second Hour, Minute, Second String to ASCII value Asc String to number Val Time to serial number TimeSerial, TimeValue TIP: Note that you can cast variables from one type to another in Visual Basic using the functions CBool(), CByte(), and so on. Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\088-091.html (3 of 4) [3/14/2001 1:28:36 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Setting Variable Scope Youve just finished creating a new dialog box in your greeting card program, and it s a beauty. However, you realize theres a problem: the user enters the new number of balloons to display the greeting card in TextBox1 of the dialog box, but how do you read that value in the rest of the program when the user closes the dialog box? Its tempting to set up a global variable, intNumberBalloons, which you fill in the dialog box when the user clicks on the OK button. That way, youll be able to use that variable in the rest of the program when the dialog box is closed. But in this case, you should resist the temptation to create a global variableits much better to refer to the text in the text box this way (assuming the name of the dialog form you ve created is Dialog): intNumberBalloons = Dialog.TextBox1.Text Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\088-091.html (4 of 4) [3/14/2001 1:28:36 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com This avoids setting up a global variable needlessly. In fact, one of the most important aspects of Visual Basic programming is variable scope. In general, you should restrict variables to the smallest scope possible. There are three levels of variable scope in Visual Basic, as follows: " Variables declared in procedures are private to the procedure. " Variables declared at the form or module level in the form or modules (General) section using Dim, ReDim, Private, Static, or Type are form- or module-level variables. These variables are available throughout the module. " Variables declared at the module level in the modules (General) section using Public are global and are available throughout the project, in all forms and modules. Note that you cannot use Public in procedures. You can get an overview of the scope of variables in a Visual Basic project in Figure 3.1. Figure 3.1 Visual Basics variable scope schematic. For more information, see the discussion of variable scope in Chapter 1. TIP: If you use the Option Private Module statement in a module or form, all variables in the module or form become private to the module, no matter how they are declared. Verifying Data Types You can change a variables type with ReDim in Visual Basic, assign objects to variables using Set, and even convert standard variables into arrays. For these and other reasons, Visual Basic has a number of data verification functions, which appear in Table 3.3, and you can use these functions to interrogate objects and determine their types. Table 3.3 Data verification functions. Function Does This IsArray() Returns True if passed an array IsDate() Returns True if passed a date IsEmpty() Returns True if passed variable is uninitialized IsError() Returns True if passed an error value IsMissing() Returns True if value was not passed for specified parameter in procedure call IsNull() Returns True if passed NULL IsNumeric() Returns True if passed a numeric value IsObject() Returns True if passed an object Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\091-095.html (1 of 3) [3/14/2001 1:28:40 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Note in particular the IsMissing() function, which many programmers dont know about; this function tells you if the call to the current procedure included a value for a particular variant. For example, heres how we check if the call to a subroutine CountFiles() included a value in the optional parameter intMaxFiles: Sub CountFiles(Optional intMaxFile As Variant) If IsMissing(intMaxFile) Then 'intMaxFiles was not passed Else End If End Sub Declaring Arrays And Dynamic Arrays Its time to start coding that database program. But wait a momenthow are you going to handle the data? Its just a simple program, so you dont want to start tangling with the full Visual Basic database techniques. An array would be perfect; how do you set them up again? You can use Dim (standard arrays), ReDim (dynamic arrays), Static (arrays that dont change when between calls to the procedure theyre in), Private (arrays private to the form or module theyre declared in), Public (arrays global to the whole program), or Type (for arrays of user-defined types) to dimension arrays. Well start with standard arrays now. Standard Arrays You usually use the Dim statement to declare a standard array (note that in Visual Basic, arrays can have up to 60 dimensions): Dim [WithEvents] varname [([subscripts])] [As [New] type] [, [WithEvents] varname [([subscripts])] [As [New] type]] The WithEvents keyword is valid only in class modules. This keyword specifies that varname is an object variable used to respond to events triggered by an ActiveX object. The varname identifier is the name of the variable you are declaring. You use subscripts to declare the array. You set up the subscripts argument this way: [lower To] upper [, [lower To] upper] The New keyword enables creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it. The type argument specifies the data type of the variable, which may be Byte, Boolean, Integer, Long, Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\091-095.html (2 of 3) [3/14/2001 1:28:40 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. If you dont specify a type, the default is Variant, which means the variable can act as any type. Here are a few examples of standard array declarations: Private Sub Command1_Click() Dim Data(30) Dim Strings(10) As String Dim TwoDArray(20, 40) As Integer Dim Bounds(5 To 10, 20 To 100) Strings(3) = "Here's a string!" End Sub TIP: You use the Option Base statement at the form- or module-level to set the lower bound for all arrays. The default value is 0, but you can use either of these two statements: Option Base 0 or Option Base 1. Dynamic Arrays You can use the Dim statement to declare an array with empty parentheses to declare a dynamic array. Dynamic arrays can be dimensioned or redimensioned as you need them with the ReDim statement (which you must also do the first time you want use a dynamic array). Heres how you use ReDim: ReDim [Preserve] varname (subscripts) [As type] [, varname(subscripts) [As type]] You use the Preserve keyword to preserve the data in an existing array when you change the size of the last dimension. The varname argument holds the name of the array to (re)dimension. Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\091-095.html (3 of 3) [3/14/2001 1:28:40 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The subscripts term specifies the dimensions of the array using this syntax: [lower To] upper [,[lower To] upper] The type argument specifies the type of the array. The type may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. This is one of those topics that is made easier with an example, so heres an example using dynamic arrays, where we declare an array, dimension it, and then redimension it, like this: Private Sub Command1_Click() Dim DynaStrings() As String ReDim DynaStrings(10) DynaStrings(1) = "The first string" 'Need more data space! ReDim DynaStrings(100) DynaStrings(50) = "The fiftieth string" End Sub The Array() Function You can also use the Array() function to create a new variant holding an array. Heres how you use Array(): Array(arglist) The arglist argument is a list of values that are assigned to the elements of the array contained within the variant. Heres an example that creates an array with the values 0, 1, and 2: Dim A As Variant A = Array(0,1,2) TIP: If you dont specify any arguments, the Array() function returns an array of zero length. Well finish this topic with a summary of array-handling techniques. Array-Handling Techniques Summary Visual Basic has a number of statements and functions for working with arrays, and they appear in overview in Table 3.4 for easy reference. Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\095-096.html (1 of 4) [3/14/2001 1:28:42 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Table 3.4 Array-handling techniques. To Do This Use This Verify an array IsArray Create an array Array Change default lower limit Option Base Declare and initialize an array Dim, Private, Public, ReDim, Static Find the limits of an array LBound, UBound Reinitialize an array Erase, ReDim Declaring Subroutines Everyone knows about subroutines: theyre the handy blocks of code that can organize your code into single-purposed sections to make programming easier. Unlike functions, subroutines do not return values; but like functions, you can pass values to subroutines in an argument list. For references sake, heres how you declare a subroutine: [Private | Public | Friend] [Static] Sub name [(arglist)] [statements] [Exit Sub] [statements] End Sub The Public keyword makes a procedure accessible to all other procedures in all modules and forms. The Private keyword makes a procedure accessible only to other procedures in the module or form in which it is declared. The Friend keyword is used only in class modules and specifies that the procedure is visible throughout the project, but not visible to a controller of an instance of an object. The Static keyword specifies that the procedures local variables should be preserved between calls. The name identifier is the name of the procedure. The arglist identifier is a list of variables representing arguments that are passed to the procedure when it is called. You separate multiple variables with commas. The statements identifier is the group of statements to be executed within the procedure. The arglist identifier has the following syntax: Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\095-096.html (2 of 4) [3/14/2001 1:28:42 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [Optional] [ByVal | ByRef] [ParamArray] varname [()] [As type] [= defaultvalue] In arglist, Optional means that an argument is not required; ByVal means that the argument is passed by value; ByRef means that the argument is passed by reference (ByRef is the default in Visual Basic); ParamArray is used as the last argument in arglist to indicate that the final argument is an array of Variant elements; varname is the name of the variable passed as an argument; type is the data type of the argument; and defaultvalue is any constant or constant expression, which is used as the arguments default value if youve used the Optional keyword. TIP: When you use ByVal, you pass a copy of a variable to a procedure; when you use ByRef, you pass a reference to the variable, and if you make changes to that reference, the original variable is changed. The Exit Sub keywords cause an immediate exit from a Sub procedure. Finally, End Sub ends the procedure definition. You call a Sub procedure using the procedure name followed by the argument list. Heres an example of a subroutine: Sub CountFiles(Optional intMaxFile As Variant) If IsMissing(intMaxFile) Then 'intMaxFiles was not passed MsgBox ("Did you forget something?") Else End If End Sub TIP: For an overview of how to comment procedures, see the discussion in Chapter 1. Declaring Functions There are two types of procedures in Visual Basic: subroutines and functions. Subroutines can take arguments passed in parentheses but do not return a value; functions do the same but do return values (which can be discarded). A function is a block of code that you call and pass arguments to, and using functions helps break your code up into manageable parts. For references sake, heres how you declare a function: [Private | Public | Friend] [Static] Function name [(arglist)] [As type] Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\095-096.html (3 of 4) [3/14/2001 1:28:42 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [statements] [name = expression] [Exit Function] [statements] End Function Visual Basic 6 Black Book:The Visual Basic Language http://24.19.55.56:8080/temp/ch03\095-096.html (4 of 4) [3/14/2001 1:28:42 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... up a Visual Basic Timer object and have a procedure called, say, every second http:/ /24 .19.55. 56: 8080/temp/ch03\114-115.html (3 of 4) [3/14 /20 01 1 :28 :58 AM] Visual Basic 6 Black Book: The Visual Basic Language Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com http:/ /24 .19.55. 56: 8080/temp/ch03\114-115.html (4 of 4) [3/14 /20 01 1 :28 :58 AM] Visual Basic 6 Black Book: The Visual Basic. .. http:/ /24 .19.55. 56: 8080/temp/ch03\109-114.html (2 of 4) [3/14 /20 01 1 :28 :55 AM] Visual Basic 6 Black Book: The Visual Basic Language Print Screen {PRTSC} Right Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com arrow {RIGHT} Scroll Lock {SCROLLLOCK} Tab {TAB} Up arrow {UP} F1 {F1} F2 {F2} F3 {F3} F4 {F4} F5 {F5} F6 {F6} F7 {F7} F8 {F8} F9 {F9} F10 {F10} F11 {F11} F 12 {F 12} F13 {F13}... therefore, is just like running into a breakpointthe debugger will come up http:/ /24 .19.55. 56: 8080/temp/ch03\1 16- 1 16. html (2 of 2) [3/14 /20 01 1 :28 :59 AM] Visual Basic 6 Black Book: Managing Forms In Visual Basic Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Chapter 4 Managing Forms In Visual Basic If you need an immediate solution to: Setting Title Bar Text Adding/Removing... themselves writing, for example, a C++ loop in the middle of a Visual Basic program and being taken by surprise when the compiler objects To make it easier, well include examples here of all the Visual Basic loops, starting with the Do loop http:/ /24 .19.55. 56: 8080/temp/ch03\105-109.html (2 of 5) [3/14 /20 01 1 :28 :51 AM] Visual Basic 6 Black Book: The Visual Basic Language The Do Loop Simpo PDF Merge and Split Unregistered... intGrade2, intGrade3, NumberStudents As Integer intGrade1 = 60 intGrade2 = 70 intGrade3 = 80 NumberStudents = 3 MsgBox ("Average grade = " &_ Str(intGrade1 + intGrade2 + intGrade3 / NumberStudents)) End Sub When you run the program, however, it calmly informs you that the average score is 1 56. 666 666 67 That doesnt look so goodwhats wrong? http:/ /24 .19.55. 56: 8080/temp/ch03\1 02- 105.html (1 of 4) [3/14 /20 01... one of the high points of Visual Basic However, because of the heterogeneous nature of their contents, they dont necessarily lend themselves to tight and uniform coding practices (which makes some C and C++ programmers look down their noses at Visual Basic) http:/ /24 .19.55. 56: 8080/temp/ch03\109-114.html (1 of 4) [3/14 /20 01 1 :28 :55 AM] Visual Basic 6 Black Book: The Visual Basic Language Sending Keystrokes... can use The Parts Of An MDI Form Besides standard forms, Visual Basic also supports MDI forms An MDI form appears in Figure 4 .2 Figure 4 .2 An MDI form http:/ /24 .19.55. 56: 8080/temp/ch04\117- 123 .html (2 of 4) [3/14 /20 01 1 :29 :07 AM] Visual Basic 6 Black Book: Managing Forms In Visual Basic You can see that an MDI form looks much like a standard form, with one major difference, of PDF MergeclientSplit Unregisteredform... programs There are times when you want to end a program without any further adofor example, to make an Exit menu item active How do you do that? http:/ /24 .19.55. 56: 8080/temp/ch03\1 16- 1 16. html (1 of 2) [3/14 /20 01 1 :28 :59 AM] Visual Basic 6 Black Book: The Visual Basic Language You use the End statement This statement stops execution of your programbut note that it does soMerge and Split Unregistered that no... Work with ASCII Asc, Chr and ANSI values http:/ /24 .19.55. 56: 8080/temp/ch03\0 96- 101.html (4 of 4) [3/14 /20 01 1 :28 :45 AM] Visual Basic 6 Black Book: The Visual Basic Language Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Converting Strings To Numbers And Back Again Youre all set to write your SuperDeluxe calculator program in Visual Basicbut suddenly you realize that the user will... Minimizing/Maximizing And Enabling/Disabling Forms From Code http:/ /24 .19.55. 56: 8080/temp/ch04\117- 123 .html (1 of 4) [3/14 /20 01 1 :29 :07 AM] Visual Basic 6 Black Book: Managing Forms In Visual Basic In Depth PDF Merge and Split Unregistered Version - http://www.simpopdf.com Simpo In this chapter, well take a look at handling forms in Visual Basic Theres a great deal to see about form handling, and well look . score is 1 56. 666 666 67. That doesnt look so goodwhats wrong? Visual Basic 6 Black Book: The Visual Basic Language http:/ /24 .19.55. 56: 8080/temp/ch031 02- 105.html (1 of 4) [3/14 /20 01 1 :28 :48 AM] Simpo. in Visual Basic using the functions CBool(), CByte(), and so on. Visual Basic 6 Black Book: The Visual Basic Language http:/ /24 .19.55. 56: 8080/temp/ch0388-091.html (3 of 4) [3/14 /20 01 1 :28 : 36. identifier has the following syntax: Visual Basic 6 Black Book: The Visual Basic Language http:/ /24 .19.55. 56: 8080/temp/ch0395-0 96. html (2 of 4) [3/14 /20 01 1 :28 : 42 AM] Simpo PDF Merge and Split Unregistered

Ngày đăng: 14/08/2014, 01:20

Từ khóa liên quan

Mục lục

  • Visual Basic 6 Black Book

    • Table of Contents

    • Introduction

    • Whats on the CD-Rom

    • About the Author

    • Chapter 1 - Visual Basic Overview

      • Chapter 1 - Continued

      • Chapter 1 - Continued

      • Chapter 1 - Continued

      • Chapter 1 - Continued

      • Chapter 1 - Continued

      • Chapter 1 - Continued

      • Chapter 1 - Continued

      • Chapter 2 - The Visual Basic Development Environment

        • Chapter 2 - Continued

        • Chapter 2 - Continued

        • Chapter 2 - Continued

        • Chapter 2 - Continued

        • Chapter 2 - Continued

        • Chapter 2 - Continued

        • Chapter 2 - Continued

        • Chapter 3 - The Visual Basic Language

          • Chapter 3 - Continued

          • Chapter 3 - Continued

Tài liệu cùng người dùng

Tài liệu liên quan