One of the beginners of VB

Source: Internet
Author: User
Tags case statement compact uppercase letter

1.1 key knowledge points

1. VB features, installation and startup

Understand the object-oriented, visual, and event-driven features of VB.

2. VB integrated development environment

Beginners can learn how to use the menu bar, toolbar, Toolbox window, attribute window, code window, and project resource manager window.

3. Concept of VB object, three elements of object attributes, methods, and events

4. process of creating a VB Application

5. Master the common attributes, methods, and events of forms, labels, text boxes, and command button controls.

6. Composition and Management of VB Applications

Composition of the VB Application:. one or more vbp engineering files ). frm Form file, automatically generated. frx binary files can also be. bas and. cis file (SEE ).

After creating, editing, and debugging an application, do not omit a file when saving it. Master the method of adding or deleting a form in the project, and distinguish between the form name and the Form file name.

7. Create an installation disk

To view the packaging and expansion result files.

8. VB helps you install and use the system

VB helps install the system disk MSDN. the most convenient way to use VB is to select the target object and press the F1 key to display the help information of this object.

1.2 Common Errors and difficulties

1. punctuation Error

In VB, only Chinese Punctuation Marks can be used. Any Chinese Punctuation Marks generate an "invalid character" error during program compilation, which is displayed in red in this line. Do not use Chinese Punctuation Marks after entering VB. The subscripts of the Chinese and Western States are as follows.

Comparison of punctuation marks in Chinese and Western States

Spanish status
,
.
'
"
;
_
<

Chinese Status
,
.
'
"
:
--

2. letters and numbers are similar in shape.

L lowercase letters "1" and numbers "l" are almost the same, and O lowercase letters ". "And number" 0 "is also difficult to distinguish, which should be paid attention to when entering the code, avoid being used as a variable name separately.

3. An error occurred while writing the object Name attribute.

Each control created on the form has a default name, which uniquely identifies the control object in the program. The system provides default object names for each created object, such as Text1, Text2, Command1, and label1. You can change the Properties window (name) attribute to a readable name, such as txtInput, txtOutput, and cmdOk. For beginners, it is easier to use the default Control name because the program is relatively simple and the control objects are rarely used.

When the object name in the program is incorrectly written, the system displays the "required object" Information and clouds the statements with a yellow background. You can check the objects used in the form in the "Object List" box in the code window.

4. confusion between the Name and Caption attributes

The value of the Name attribute uniquely identifies the control object in the program and is invisible to the form. The value of the Caption attribute is displayed on the form.

5. An error occurred while writing the property name and Method Name of the object.

When the property name and method name of an object in the program are incorrectly written, the VB system displays "method or data member not found" information. When writing program code, try to use the function of automatically listing members. That is, when you enter the control object name and period, the system automatically lists the available properties and methods of the control object in running mode, you can press the Space key or double-click the mouse to reduce input and prevent such errors.

6. variable name Error

The variable name declared by Dim is used later to indicate the same variable and the variable name is written incorrectly. When VB is compiled, it is considered to be two different variables. For example, the following section calculates 1 ~ The Sum of 100 is placed in the Sum variable:

Dim sum As Integer, I As Integer

Sum = 0

For 1 to 100

Sum = Sun + I

Next I

Print Sum

The displayed result is 100. The reason is that Sum, the variable name on the Right of Sum = Sun + I, is written as Sun. VB has two methods to declare variables. You can use the variable declaration statement to explicitly declare the variables, or you can use the implicit Declaration, that is, directly use the statements without declaration. If the preceding variable name is written incorrectly, the system allocates memory units for two different variables, which leads to incorrect calculation results. Therefore, to prevent such errors, you must restrict them to Explicit declarations, that is, add the Option Explicit statement in the General Declaration section.

7. incorrect statement writing position

In VB, except for statements that use Dim to declare variables in the "General Declaration" section, any statement should be in the event process, otherwise, the message "invalid external process" is displayed. To initialize a module-level variable, it is generally placed in the Form Load () event process.

8. You have no intention of forming a control array.

To create multiple command buttons on the form, some readers create a command button control first, and then copy and paste the control. The system displays:

There is already a control named "Command1 ". Create a control array? If you click the "yes" button, the system creates a control array named Command1. To program the Click event process of the control, the system displays the following frameworks:

Private Sub commandateclick (Index As Integer)

End Sub

Index indicates the subscript of the control array.

If it is not a control array, the frame of the Click event process is:

Private Sub commandementclick ()

End Sub

Note that the control array is not used until Chapter 4 array is learned.

9. Locate the problem in the Print method

Positioning is controlled by the Tab, Spc function, and the last comma, semicolon, and unsigned. In VB, all the parameters in the Print method are used to achieve the desired results, but it is difficult for beginners to grasp them.

(1) differences between Tab (n) and Spc (n)

Tab (n) is located in column n starting from column 1st on the left. If the current position of the print column exceeds n, it is located in column n on the next row, this is often difficult to locate. Most tabs are used in format positioning.

Spc (n) from the previous printing position, there are n blank spaces. For example, the following section shows the difference between Tab and Spc, and the effect.

Private Sub Commandl_Click ()

Print "1234567890 ",

Print Tab (1); "**" '; Tab (2); "%"; spc (2); "$"

End Sub

 

 

 

(2) compact format ";" use of semicolons

Compact format ";", that is, there is no interval between output items. However, for the numeric type, the system automatically empty one column between output items. Because the numeric system automatically adds a signed bit, the actual null column is the value greater than zero. There is no space between character types.

For example, the following program section shows the effect.

 

 

 

Private Sub commandementclick ()

Print 1;-2; 3

Print "1234"; "5678"

Print "A"; "B"; "C"; "D", "E", "F"

End Sub

In this example, the differences between numbers and characters in compact format should be distinguished.

10. The corresponding file cannot be found when the project is opened.

Generally, a simple application should also consist of a project. vbp file and a form. frm file. The project file records the names of all files (Form. frm files, standard module. bas files, class module. cls files, etc.) in the project and the path stored on the disk.

If you copy a file to a floppy disk and save it after the computer finishes, but do not copy a file, the next time you open the project, the system displays "file not found ". In addition to the VB environment, the Windows resource manager or the DOS command is used to rename the Form file, while the original file name is recorded in the project file, this will also display "file not found" when opening the project ".

Solution to this problem: first, modify. file name in the vbp Project File: Second, add the renamed form to the project by using the "existing" option in "add form" in the "project" menu.

Chapter 2 Basic and Sequence Structure of VB Language

2.1 key knowledge points

1. vbprogram writing rules

(1) VB code writing rules

1) The program does not distinguish between uppercase and lowercase letters. AB is equivalent to AB;

2) the system automatically converts the user program code:

L for keywords in VB, the first letter is converted to uppercase and the rest are converted to lowercase letters.

L if a keyword is composed of multiple English words, the first letter of each word is converted to uppercase.

L for User-Defined variables and process names, subject to the first definition, the input will be automatically converted to the first defined form

(2) Statement writing rules

1) multiple statements can be written on the same line, separated by colons (:).

2) A single-row statement can be written in multiple lines, followed by a hyphen (-): space and underscore _

3) a row can contain up to 255 characters

(3) program annotation Method

1) The whole line of comments generally starts with Rem and can also be indicated by an ampersand ';

2) Comments guided by an ampersand can be either an entire line or directly placed behind the statement, which is the most convenient;

3) You can use "set comment block" and "uncomment block" in the "edit" toolbar to set multi-line comments.

2. Data Types provided by VB

VB provides a wide range of data types (see Table 1.3.1 In the tutorial). Each data type is represented by a keyword or type character. Different data types occupy different storage spaces, you can use the appropriate type based on your actual needs. In addition to the data type, VB also provides the construction type, that is, the array and user-defined type (equivalent to the record type ).

3. Variables and constants

(1) variables

L variable naming rules:

☆It must start with a letter or Chinese character. It may consist of letters, Chinese characters, numbers, or underscores (_). The length must be less than or equal to 255 characters;

☆Keywords in VB cannot be used and should not be the same as standard function names in VB; for example, Dim and Sin

☆In VB, variables are case-insensitive. Generally, the first letter of a variable is in upper case, and the rest are in lower case. constants are all in upper case.

☆To increase the readability of the program, you can add a prefix before the variable name to indicate the Data Type of the variable.

L variable Declaration: variables of various types can be declared using Dim and other declaration statements or type operators, or variables with Variant types can be directly used without declaration. To make the program run securely and reliably, it is better to use explicit declarations for the variables used.

L initial value of the variable: by default, the numeric variable is zero and the numeric variable is null (... Q), the object variable is Nothing.

(2) Constants

In VB, there are three types of constants:

· Direct constants, such as 1, 1.23, & Hab, 0.123El, "1234asd", #2000/5/5 #, True, and False.

· User-Defined constants, for example, Const PI = 3.14159.

· Constants provided by the VB system, such as vbEmpty, vbInteger, and vbNormal.

4. Operators and priorities

Arithmetic Operators-, ^, * Or/,/, Mod, +, or-from high to low

Character operators + or

Relational operators =,>, >=, <, <=, <>, Is, and Like

Logical operators Not, And, Or, Xor, Eqv, Imp are high to low

5. Expression writing and value types

Writing rules: You can write data from left to right on a row without distinction between high and low: operators in expressions can be enclosed in parentheses to change the priority of an operation or increase the degree of deviation of an expression. Square brackets or curly braces cannot be used. Parentheses can appear multiple times, but must be paired.

Value Type: In arithmetic expressions, different data types are displayed, which are converted to data types with high precision.

6. Common functions

VB provides a variety of functions. In this tutorial, some common functions are listed by arithmetic, String, date and time, conversion, format, and other types, for the complete function form and examples, see VB help. There are two methods to query: For a known function name, select a function name and Press F1: Unknown Function Name. after entering the VB help, go to the "directory" tab, select the "Visual Basic document" directory, and then select "function" in "Language Reference" under "Reference ".

7. Assignment Statement

The value "=" can only be a variable on the left; only one variable can be assigned at a time.

8. Interaction functions and processes with users

InputBox function and MsgBox function or process.

2.3 Common Errors and difficulties

1. Logic expression writing error. The logical error is formed without syntax error in VB.

For example, a mathematical representation of variable X in a certain range of values, such as 3 ≤ x <10, is represented by a logical expression of VB. Some Readers write VB expressions as follows:

3 <= x <10

At this time, syntax errors will be generated in other languages, but no syntax errors will be generated in VB. The program can run, but the value of the expression will always be true regardless of the value of X, this leads to the illusion that the program can run normally, and the result is incorrect.

In VB, when two variables or constants of different types are involved in the operation, the type conversion function with high self-moving precision is available. For example, the value of the logical constant tme to the numeric type is-1, the value of false is 0, and the value of the numeric type is not 0 to the logic type is true, and the value of 0 is false. Similarly, numeric operations are performed on numeric characters.

For example, the result displayed in the printtrue + 3' statement is 2.

Print "123" + 100 "displays 223 results

Print #5/1/2000 # + 3': 00-5-4

For this reason, the expression:

3 <= x <10

(1)

(2)

The calculation process of the value is: Calculate 3 <= x based on the value of X, and the result is always true or false; then the value (-1 or 0) and 10 are always true. The correct VB expression is written as follows:

3 <= x and x <10

2. assign values to multiple variables at the same time, and generate logical errors without causing syntax errors in VB

For example, if you want to assign initial value 1 to the integer variables X, Y, and Z at the same time, some Readers write the following assignment statement:

X = y = z = 1

In C language, the preceding statement can assign values to multiple variables at the same time, while in VB, only one variable can be assigned a value within a value assignment statement, however, the preceding statement does not generate a syntax error. After running, the result in X, Y, and Z is 0.

The reason is that VB regards y = z = 1 as an expression, and then assigns the result of the expression to x. In VB, the initial value of the default numeric variable is 0. According to the analysis of error 1 above and so on, the result of the expression y = z = l is 0, therefore, the value of x is 0, y, and z. The default value is o.

3. An error occurred while writing the standard function name.

VB provides many standard functions, such as IsNumeric (), Date (), and LeR. When the function name is incorrectly written, for example, if IsNumeric is written as IsNummeric, the system displays "subprogram or function undefined" and selects the wrong function name to remind the user to modify it.

[Prompt]

The most convenient way to determine whether a function name, control name, attribute, and method is wrong is to press Enter after the statement is written, the system automatically converts the recognized name to an uppercase letter. Otherwise, the name is incorrect.

4. endless loop of programs caused by checking Data Validity

When inputting data, you often need to check the validity of the input data to ensure the correctness of the program running. For example, in the experiment: 1st, the input temperature must be a number. Otherwise, the original input content will be deleted and the focus will still be located in the text cabinet. The following table describes how to set attributes. The program section is shown in Figure 2.2.2.

Table 2.2.1 control attributes

Control name TabIndex

Text1 2

Text2 3

Command1 4

Command1 5

Private Sub text=lostfocus ()

If Not IsNumeric (Text1) Then

Text1 = ""

Text1.SetFocus

End If

EndSub

Private Sub Text2_LostFocus ()

If not isnumeric (text2) then

Text2 = ""

Text2.setfocus

End if

End sub

When the input of the Fahrenheit temperature (text1) is incorrect, the focus is continuously flashing at text2, and the program generates an endless loop.

The reason is that when the textl input ends, press the tab key to trigger the textl lostfocus event, and the focus has reached text2. However, when the textl text box input data is incorrect, run textl. setfocus: the focus is pulled back from text2 to textl, And the text2_lostfocus event is triggered. In this case, text2.setfocus is executed to pull the focus from text1 back to text2, this staggered process leads to an endless loop.

When the temperature (text2) is incorrect, the program runs normally. When the text2 input ends, press the tab key, and the focus has reached commanl, no endless loop is generated.

To solve the problem of endless loops during incorrect text1 input, you only need to change the if expression of the private sub text2_lostfocus () event if not isnumeric (text2) then to iftext2 <> "" and not isnumeric (text2) then.

5. How to terminate an endless loop

When an endless loop (especially the loop structure introduced in chapter 4) is generated due to poor consideration during programming, the endless loop can be terminated by pressing CTRL + break at the same time, find out the cause of the endless loop and modify the program.

6. Declaring local variables and form-level variables

In the vbprogram, in addition to a large number of control objects, some variables are also used to temporarily store some intermediate results. The declaration of these variables can be placed in the "General Declaration" section outside the process (called form-level variables, described in section 3.7.4 of the tutorial), or in the process (called local variables ), how to place these variables is a headache for beginners. Differences between the two: Form-level variables can be used in all the processes of the form: while local variables can only be used in the process where the variables are located, that is, the storage space is allocated as the execution of the process, when an EndSub statement is executed, the allocated memory space is recycled, and the value of the variable is also lost.

For example, in question 2 and 2nd of the experiment, there are four processes in the form of method 1. Three variables a, B, c, and, therefore, the declaration of these variables should be in the "General Declaration" section. Otherwise, the values of a, B, and c variables are zero during the Click event. In method 2, there is only one event process. variables a, B, and c are declared as process-level variables. Of course, declarations have the same effect as form-level variables.

Method 1: Method 2:

Dimag, B #, c # Pfiv ~ ESubForm-Click ()

Private Sub Textl_LostFocus () Dima #, B #, c #

... 'Assign a value to variable... 'Variables a, B, and c are used.

EndSub

Private Sub Text2_LostFocus ()

... 'Assign a value to variable B

EndSub

Private Sub Text3_LostFocus ()

... 'Assign a value to variable c

EndSub

Private Sub commandementclick ()

... 'Variables a, B, and c are used.

EndSub

7. In the Form Load event, the SetFocus method does not work.

The reason is the same as the print method, because the system cannot synchronously use the setfocus method to locate the control focus when the form is loaded into the memory. Solution: In the Properties window, set the value of tablndex to the control whose focus is to be located. .

8. Focus movement between multiple text boxes during program running

Method-: Press "tab. In this case, you do not need to program it. You can use the functions provided by the system to conveniently move between controls. To determine which control to exit or enter, use the lostfocus ''or" control _ gotfocus ''event to determine.

Method 2: Press "enter. In this case, you must use the keypress event programming method. The program section is as follows:

Private sub a text box _ keypress (keyascii as integer)

If keyascii = 13 then

Another control. setfocus

End if

...

End sub

Chapter 3 selection Structure

3.1 key knowledge points

1. Two formats and usage of a unilateral if statement

(1) If <expression> then (2) If <expression> then <Statement>

<Statement block>

End if

The expression can be any expression, that is, an arithmetic, character, link, or logical expression. It is not based on the value of the expression. Is true, and 0 is false.

If of multiple rows must be paired with endlf; the format of a single row does not contain the end if keyword.

2. Two formats and usage of bilateral if statements

(1) If <expression> then (2) If <expression> then <Statement 1> else <Statement 2>

<Statement Block 1>

Else

<Statement Block 2>

End If

3. Format and use of multilateral IF statements

If <expression 1> Then

<Statement Block 1>

ElseIf <expression 2> Then

<Statement Block 2>

[Else

<Statement Block n + 1>]

End If

There cannot be spaces between Else If.

4. nesting and use of IF Statements

If <expression 1> Then

...

If <expression 11> Then

...

End If

...

End If

Distinguishes nested hierarchies. Each Endlf is paired with the nearest If. It is written as a tooth shape for easy differentiation and matching.

5. Format and usage of the Select Case statement

Format:

Select Case <variable or expression,

Case <expression List 1>

<Statement Block 1>

Case <expression List 2>

<Statement block>

...

[Case Else

<Statement Block n + 1>]

End Select

<Variable or expression> can only be used to judge a variable in multiple situations. <expression list I> cannot identify variables that appear in "variables or expressions.

6. Form and use of conditional test functions

IIf (<condition expression>, value when the condition is True, and value when the condition is False)

Choose (&

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.