Beginner VB II

Source: Internet
Author: User
Tags case statement variable scope

Lt; numeric type variable>, return value of 1, return value of 2 ...)

Switch (<condition expression 1>, value when condition expression 1 is true

[, <Condition expression 2>, value when condition expression 2 is true…])

3.3 Common Errors and difficulties

1. The final sentence of pairing is missing in the selection structure.

In the multi-row if BLOCK statement, end if statements should be paired. Otherwise, the system will display a compilation error of "block if no end if" at runtime.

The Select case statement should also have the corresponding endselect statement.

2. Write the else if keyword and Expression of conditional expressions for multilateral Selection

The keyword else if in the multilateral selection else if clause cannot contain spaces, that is, it cannot be written as else if.

When multiple condition expressions are represented, the minimum or maximum conditions should be represented in sequence to avoid filtering conditions. For example, if the percentage score mark of a course is known to be input, the score of the corresponding five-level system must be displayed. The evaluation conditions are as follows:

The syntax is correct for the following expressions, but the results are different after execution. Which of the following statements are correct? What are the errors?

In the answers given below, method 1, method 2, and Method 5 are correct. For other errors, please analyze the causes.

Method 1: Method 2: method 3:

If Mark> = 90 then if Mark <60 then if Mark> = 60 then

Print "excellent" print "fail" print "pass"

Elseif mark> = 80 then elseif mark <70 then elseif mark> = 70 then

Print "good" print "pass" print "medium"

Elseif mark> = 70 then elseif mark <80 then elselfmark> = 80 then

Print "good" in print "print"

Elseifmark>-60 then elseif mark <90 then elselfmark> = 90 then

Print "pass" print "good" print "excellent"

Else

Print "pass" print "excellent" print "fail"

End if end if

Method 4: Method 5:

If Mark> = 90 then if Mark> = 90 then

Print "excellent" print "excellent"

Elseif80 <= mark <90 then elseif80 <= mark and Mark <90 then

Print "good" print "good"

Elseif70 <= mark <80 then elseif70 <= mark and Mark <80 then

Print "medium" print "medium"

Elseif60 <= mark <70 then elseif60 <= mark and Mark <70 then

Print "pass" print "pass"

Else

Print "fail" print "fail"

End if end if

3. Use of select case statements

(1) variables in "variables or expressions" cannot be used in "expression list I. For example, the preceding example of multilateral selection is changed to the Select Case statement. The variable mark appears in the Case clause of method 1. The Case Else clause is always executed no matter the value of mark, the running result is incorrect. method 2 and method 3 are correct.

Method 1: Method 2: method 3:

Select Case mark

Case mark> = 90 Case Is> = 90 Case Is> = 90

Print "excellent"

Case mark> = 80 Casels> = 80 Case 80To 89

Print "good"

Casemark> = 70 Case Is> = 70 Case 70To 79

Print "medium"

Case mark> = 60 Case Is> = 60 Case 60TO 69

Print "pass" Prim "pass" Print "pass"

Case Else

Print "fail"

End Select

(2) multiple variables cannot appear in "variables or expressions. The judgment on the scholarship of the three courses in experiment 3 and 5th can only be performed using the If statement instead of the SelectCase statement. For example, some readers use the following statement:

Select Case markl, mark2, mark3

Case (markl + mark2 + mark3)/3> = 95

Print "First Prize"

End Select

In this Case, an error occurs in the "Select Case markl, mark2, mark3" statement line: At the same time, Case (markl + mark2 + mark3)/3> = 95 is also incorrect.

Chapter 4 Loop Structure

4.1 key knowledge points

1.... Next loop structure form and usage

For <cyclic variable >=< initial value> To <End value> [Step <Step size>]

<Loop body>

Next <cyclic variable>

It is often used when the number of loops is known. The step size can be positive or negative, and can be an integer or a real number. Grasp the calculation of the number of cycles: when the cycle variable (step size is positive) is greater than the end value, the cycle ends.

For example, the program segment is the value of sin displayed every 100:

(1) Fori = 0 To 360 Stepl0 (2) For x = 0To 6.28 Step 6.28/36

Print sin (I * 3.14/180) Print sin (x)

NextiNextx

(3) For j = 360 To 0 Step-10

Print sin (360-j) * 3.14/180)

Next j

2. Do... Loop structure and usage

There are five forms based on different combinations:

1) Unconditional loop 2) when the condition is true, 3) when the condition is true, no loop 4) loop first and then judge 5) loop first and then judge

Do While <condition> Do Until <condition> Do

<Cyclic body>

Loop while <condition> loopuntil <condition>

3. nested loops and precautions

In the loop body, the nested or multiple loops are called loops. Calculate the product of the number of cycles of multiple cycles by the number of cycles of each iteration.

The external body must completely contain the inner cycle structure and cannot cross.

4. other auxiliary statements

Eixt for exit the for loop statement, exit do exit the do loop, go to the five conditions to turn to the statement, end program running conclusion sentence, with statement.

4.3 Common Errors and difficulties

1. Problems with non-repeating or endless loops are mainly caused by the setting of cyclic conditions, initial values, end values, and cycle step sizes. For example, the following loop statement does not execute the loop body:

For I = 10 to 20 step-1 'step size is negative, the initial value must be greater than or equal to the final value to cycle

For I = 20 to10' The step size is positive, and the initial value must be smaller than or equal to the end value to be cyclic.

Do While false' the loop condition is never met and does not exist.

For example, the following loop statement is an endless loop:

For I = 10 to 20 step 0' step size: Zero, endless loop

Do While 1 'the loop condition is always met, and the endless loop

2. The cycle structure does not contain a pair of concluding remarks.

For... The next statement does not have a paired next statement; the DO statement does not have an ending loop statement.

3. When loops are nested, internal and external loops cross:

For I = 1 to 4

For j = 1 to 5

...

Next I

Next j

During the cross-run of the preceding loop, "invalid Next control variable reference" is displayed ".

4. Initial values assigned to the variables in the accumulative and concatenation results during accumulation and multiplication

(1) One Cycle

In a loop, the initial values of the variables that store the accumulative and multiplication results should be set before the loop statement.

For example ~ The Sum of 3 in 100 is put into the Sum variable. What is the output result in the following section?

Private SubForm_Click ()

Fori = 3 To 100 Step 3

Sum = 0

Sum = Sum + I

Next I

Print Sum

End Sub

How can we improve the results?

(2) multiple cycles

In multiple cycles, the initial values of the variables that store the accumulative and multiplication results are placed before the External Loop statements or before the internal loop statements. These values should be treated separately based on specific problems.

For example, if 30 students take three courses at the end of the period, how can we improve the average score of each student's three courses according to the following procedure?

Aver = 0

For I = 1 To 30

For j = 1 To 3

M = InputBox ("Enter the number" & j & "course score ")

Aver = aver + m

Next j

Aver = aver/3

Print aver

Nexti

Chapter 5 grouping

5.1 key knowledge points

1. Concepts of Arrays

Array: stores a group of data of the same nature, that is, the data in the array must be of the same type and nature.

Array element: a data item in the array. The use of array elements is the same as that of simple variables.

2. Static array declaration

Static array: the number of array elements is determined during declaration.

Declaration Form: Dim array name ([lower bound To] upper bound [, lower bound To] upper bound [,…]) As type

This statement declares the array name, array dimension, array size, and array type.

[Note]

The lower and upper bounds must be constants and cannot be expressions or variables: the lower bounds are omitted. The default value is 0. You can use the Option Base statement to reset the lower bounds.

3. dynamic array declaration

Declaration Form: Dim array name ()

ReDim [Preserve] array name ([lower bound To] upper bound [, [lower bound To] upper bound [,…])

[Note]

At this time, the upper and lower bounds can be variables or expressions with values. If the Preserve keyword exists, this keyword can be used to keep the original data in the array when the maximum value at the end of the original array is changed.

4. control array

An array composed of controls of the same type.

Control array creation: On the design-time form, you can copy and paste a control by using the Load method when running the program.

Control array element: the Index attribute value of the control represents the F mark of the array.

5. Array Operations

Basic operations should be mastered: array initialization, array input, array output, find the maximum (minimum) element and subscript in the array, sum, average, sort and search, etc.

5.3 Common Errors and difficulties

1. Dim array declaration

Sometimes, for the purpose of universality of the program, the upper bound of the declared array is represented by variables, as shown in the following section:

N = InputBox ("upper bound of input array ")

Dim a (1 To n) As Integer

When running the program, the error message "require constant expression" is displayed in the Dim statement. That is, on the array declared in the Dim statement, the lower bound must be a constant, not a variable.

To solve general program problems, the first is to declare a large array, which wastes some storage space; the second is to use dynamic arrays to change the above example as follows:

Dima () As Integer

N = InputBox ("upper bound of input array ")

ReDim a (1 To n) As Integer

2. array subscript out of bounds

References an array element that does not exist, that is, the subscript range is larger or smaller than that of the array declaration. For example, to form a Fibonacci series with the following 30 items:

, 34 ,..., 317811,514229, 832040

The correct program section is as follows:

Dim a (1 To 30) As Long, I %

If you change For I = 3To 30 To For I = 1 To 30, an error message "subscript out of bounds" is displayed when the program is running, because I = l at the beginning of the loop, execute to loop body Statement a (I) = a (I-2) + a (I-1), array subscript I-2, I-1 are less than the lower bound 1.

Similarly, if you change the above example: a (I) + a (I-2) + a (I-1) statement to: a (I + 2) = a (I) + a (I + 1)

When running the program, the error message "subscript out of bounds" is displayed. In this case, the array subscript is greater than the upper limit of 30.

3. array dimension error

The dimension of array declaration is inconsistent with that of array element reference. For example, the following program segment is used to form and display a matrix of 3 × 5:

Dim a (3,5) As Long

For I = 1 To 3

For j = 1 To 5

A (I) = I * j

Print a (I );"";

Next j

Print

Next I

When the program runs the (I) = I * j statement, the "dimension error" message is displayed, because the Dim statement is a two-dimensional array and a subscript is referenced.

4. Use of the wannry Function

The transport ry function can easily assign values to the array as a whole, but only variable variables or dynamic arrays enclosed by parentheses can be declared at this time. The size of the assigned array is determined by the number of assigned values.

For example, to assign values 1, 2, 3, 4, 5, 6, and 7 to array a, Table 2.5.1 lists three errors and corresponding correct assignment methods.

Table 2.5.1 using ry Function Representation

Incorrect incorrect function value assignment corrected incorrect function value assignment

Dim a (1 To 8) a = Array (1, 3, 4, 5, 6, 7) Dim a () a = Array (1, 2, 3, 4, 5, 6, 7)

Dim a As Integera = Array (1, 3, 4, 5, 6, 7) Dim aa = Array (1, 2, 3, 4, 5, 6, 7)

Dim aa () = Array (1, 2, 3, 4, 5, 6, 7) Dim aa = Array (1, 2, 3, 4, 5, 6, 7)

5. How to obtain the upper and lower bounds of Arrays

The transport ry function can easily assign values to the entire array, but how to obtain the upper and lower bounds of the array in the program can ensure that the accessed array elements are within the valid range, you can use the UBound and LBound functions to determine array access.

In the preceding example, to print the values of array a, you can use the following program section:

For I = Lbound (A) To Ubound ()

Print a (I)

Next l

6. assign values to the array

VB6.0 provides a new function that allows you to assign values to an array. However, the actual use is not so convenient and there are many restrictions. The array assignment form is as follows:

Array name 2 = array name 1

We will discuss this form: the array name 2 here, in fact, can only be declared as a variable of Varian in the previous array declaration, the size, dimension, and type of array 2 after the assignment are the same as array name 1. Otherwise, if it is declared as a dynamic or static array, for example:

Dim array name 2 () or Dim array name 2 (subscript)

When the program runs the preceding value assignment statement, it displays the error message "cannot assign values to arrays.

Therefore, in order to ensure the security and reliability of the program, it is recommended that the reader give up his/her patience. Instead of using this new function of VB6.0, the traditional loop structure should be used to assign values to the array. For this reason, we will not expand it in the tutorial.

Chapter 6 Process

6.1 Key knowledge points

1. Process Concept

The VB program consists of various processes. Apart from the fact that the VB system provides a large number of internal function processes and event processes, the VB system also allows you to customize the process as needed. Benefits of the use process: the program is concise, efficient, and easy to debug and maintain. The procedures involved in this section mainly refer to user-defined subprocesses and function processes.

2. Two types of process definitions and calls

(1) Sub-Process

Definition form: Sub <Sub-process name> [(form parameter table)]

...

End Sub

Feature: the sub-process name has no value and no type.

Call method: Call <sub-process name> [(real parameter table)]

Or: <sub-process name> [(real parameter table)]

Feature: it is an independent statement.

(2) function Process

Form: Function <Function process name> ([parameter table])

...

<Function Procedure name >=< expression>

...

End Sub

Feature: The function process name has a value and a type, and is assigned a value at least once in the process.

Call method: <Function Procedure Name> ([real parameter table])

Feature: it cannot exist independently and must be involved in expression operations.

3. parameter transfer

(1) Pass the value to the parameter.

The value passing method is to add the ByVal keyword before the form parameter, indicating that the value is passed. This method is a one-way data transfer method. During a call, values can only be passed to the form parameter by the real parameter. After a call is completed, the operation result cannot be returned to the real parameter by the real parameter. Real parameters can be constants or expressions.

(2) Transfer address

The address transfer method (ByRet) is to pass the real parameter address in the memory to the form parameter, that is, the real parameter and the form parameter share the "Address" in the memory ".

This transfer method is a two-way data transfer, that is, when the call is performed, the real parameter passes the value to the form parameter: after the call is completed, the real parameter returns the operation result to the real parameter. When a real parameter is returned, the real parameter can only be a variable, not a constant or expression.

In the process, whether to use pass-through or pass-through is considered as follows: If you want to return the result through the form parameter in the process call, use the pass-through method; otherwise, the value transmission method should be used to reduce the association between processes and facilitate program debugging. Arrays, record type variables, and object variables can only be transmitted using addresses.

In VB, the default address transfer mode is used.

4. Scope of Variables

Global variable: The variable starting with the Public keyword is a global variable, which is valid throughout the project.

Form and module-level variables: variables declared with Dim or Private keywords in the common declaration section, which are valid in the form or module.

Local variables: variables declared during the process. memory space is allocated and initialized during the call. After the call ends, the allocated space is reclaimed.

The usage rules are shown in Table 2.6.1.

Table 2.6.1 variable scope

Use range local variables form/Module-level variables global variables

Standard form Module

Acoustic Mode Dim, tatic Dim, Private

Declaration position in the process form/module's General Declaration section form/module's General Declaration Section

It cannot be accessed by other processes of this module.

It cannot be accessed by other modules, but the form name can be added before the variable name.

Static variables: add the Static keyword before the local variable declaration to maintain the value during the running process.

5. recursive call of the process

In the process of calling a sub-process or function, you can call yourself again. Such a sub-process or function process is called a recursive sub-process or a recursive function.

Conditions for forming a recursive process: recursive end conditions and values at the end: they can be expressed in recursion form, and Recursion Develops Toward the termination condition.

6. Common Algorithms

Requirements for numerical calculation: finding the maximum value (minimum value) and subscript position, sum, average value, maximum common number, minimum common multiple, prime number, number conversion, and higher order equation root (iterative method and binary method) and definite integral (rectangular, trapezoid, xinbu, and Monte Carlo ).

Non-numeric calculation: common string processing functions, sorting (selection method, bubble method, insertion method, and Merge Sorting), and searching (Order and binary method ).

6.3 Common Errors and difficulties

1. Programming Algorithm Problems

This chapter is difficult to compile programs, mainly because the idea of algorithms is difficult, which is also the most difficult stage of programming. Experience tells every beginner in programming that there is no shortcut to go through. You can read more, practice more, and learn more. Before running the machine, you must write the program and carefully analyze and check the program to improve the debugging efficiency. Every time a program passes through hard work and debugging, the joy of the past makes it hard for you to say anything.

2. Determine whether the custom process is a sub-process or a function process.

In fact, a process is an independent program unit with a certain function for multiple calls. The difference between a sub-process and a function process is that the former sub-process name has no value: the latter function process name has a value. If a return value exists in the process, the function process is used. If no return value exists in the process, the sub-process is used. If multiple values are returned in the process, the sub-process is generally used, you can also use the function process name to bring back the result through the combination of real participation parameters, and the other results are brought back through the combination of real participation parameters.

3. Determination of the number of parameters and the transfer method in the process

For beginners, the number and transmission method of parameters cannot be determined during the definition process.

Parameters are used to implement data communication between the Process and the caller. On the one hand, the caller provides an initial value for a sub-process or function process, which is implemented by passing the real parameter to the form parameter. On the other hand, the sub-process or function process passes the result to the caller, this is achieved through address transfer. Therefore, the number of parameters is determined by the above two aspects. For beginners, they often like to take all the variable life used in the process body as the form parameter, which increases the caller's burden and Error Probability: Some beginners omit the form parameter, therefore, data cannot be transmitted. The caller cannot obtain the initial value or pass the calculation result to the caller.

In VB, values and addresses are combined to participate in real parameters. The differences are as follows:

(1) In the definition form, the former adds the Val keyword before the form parameter.

(2) In terms of function, value transfer can only pass the initial value from the outside world to the process, but cannot pass the result out: address transfer can be passed in and out.

(3) If the real parameters are arrays, custom types, object variables, and so on, the form parameters can only be transmitted by address.

4. Problems Related to the actual participation parameter type

When using the address transfer method, the actual parameters involved in the call process must be of the same type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.