Let's talk about the Function Application in VB!

Source: Internet
Author: User
Tags define local



In VB, how is the function program applied?

The function process is a user-defined independent function process, similar to a sub-program. The function process can read parameters and modify statements. It can be called as an independent basic statement, or nested in a program or function. It has a return value. VB has many built-in functions, such as sin, cos, and abs. If the process needs to use a certain formula or function multiple times, there are no available parameters in VB, and the function process will be used in this case.

The syntax of the function process is:

[Private | public] [static] function (function name) ([parameter table]) [as (type)]
[Statement column] [(function name) = (expression)]
Exit gunction
[Statement column] [(function name) = (expression)]
End Function

Note: The function program can be omitted in brackets. The process of function programs is similar to that of sub programs. Only as indicates that the return value of a function is the type indicated by. There is also a function creation process. In the tool addition Process, in the Add process dialog box, the name can be customized by the user, including letters, numbers, and underscores. Select function options in type and click OK. OK! The function process is created.

Function process call:
1. Call Statement. Call (process name) [real parameter table]
2. Direct call. (Process name) [real parameter table]
3. directly call without parameters.
Example:
Function F2
F2 = "flollow me ."
End Function

About VB Function


Who can clearly introduce the VB Function process and clarify how it returns values? What is the meaning of the following code?

Dim y As Integer Private Sub Command1_Click() Dim x As Integer x=2 Text1.Text=f2(f1(x),y) Text2.Text=f1(x) End Sub Private Function f1(x As Integer)As Integer x=x+y:y=y+x f1=x+y End Function Private Function f2(x As Integer,y As Integer)As Integer f2=2*x+y End Function 

The following is my analysis process. Since I am not very good at flowcharts, I have analyzed every word.
Dim y as integer
Analysis 1 defines a global integer variable Y. Understanding of this Y is the key to the entire problem. because Y is a global variable, the value of Y is retained until the program ends. because y is not assigned a value, the system automatically assigns 0 to y. at this time, the value of Y is 0.

Private sub commandateclick () 'command button 1 Click Event
Dim X as integer
This statement defines a process-level variable X. A process-level variable indicates that the lifetime of the variable is only in the process, that is, it is valid during the command#click () process. if X appears in other processes, the system also assigns 0 to X.

Analysis 2 x = 2 assign a value to X. At this time, the value of X is 2.

Text1.text = F2 (F1 (x), Y)
The next step is the difficulty of the program. I believe that what you want is also the analysis process of this sentence. Of course, I will also analyze it in detail.
Let's briefly describe it. in this sentence, the program first calls the function F1 to obtain the value of F1, then calls the function f2 to obtain the value of F2, and then displays the value of F2 in the text box.
When the program is executed here, the program will first call the function F1 to execute the statements in F1. that is to say, when the program runs here, it first executes the statements in the private function F1 (X as integer) as integer.

Therefore, skip to this statement for analysis.

Private function F1 (X as integer) as integer
This sentence means that function F2 returns an integer variable. When calling this function, a parameter X must be provided, which is passed by address. when the program is executed here, the program automatically assigns the parameter section of the caller F1 (parameter) to X.

Analysis 3 x = x + y
This statement adds the value of X to the value of Y and then assigns it to X. because X = 2, y = 0, x = 2 + 0 = 2, that is, x = 2. (For more information about why x = 2, see Analysis 2. why is y = 0? See Analysis 1). At this time, x = 2.

Analysis 4
Y = Y + x
The meaning of this sentence is to add the value of Y to X and then assign it to Y. Because X = 2 (Why is X = 2? See analysis 3), Y = 0 (Why is y = 0? See Analysis 1), so y = Y + x = 0 + 2 = 2. In this case, the value of Y is 2, that is, y = 2.

Analysis 5
F1 = x + y
Assign the result of X + Y to F1. because X = 2 (see Analysis 3), Y = 2 (see analysis 4 ), so F1 = x + y = 2 + 4 = 4, that is, F1 = 4.

After the program is executed here, the program jumps text1.text = F2 (F1 (x), Y) because the F1 value has been obtained. because F1 = 4 (why F1 = 4? See analysis 5), so the code can be simplified:

Text1.text = F2 (4, Y)

This statement calls the function F2 and then assigns the value of F2 to the text box. The caller provides two parameters: 4 and Y.

Analysis 6
At this time, the program will jump to the private function F2 (X as integer, y as integer) as integer function execution. this function process means to assign the first parameter to X and the second parameter to y. because the first parameter of F2 (4, Y) is 4, x = 4, and the second parameter is Y, y = y.

Analysis 7
F2 = 2 * x + y
This is a mathematical operation, which means nothing more obvious. calculate the value of 2 * X + Y and then assign the result to F2, so F2 = 2 * x + y = 2*4 + 2 = 8 + 2 = 10 (Why is X equal to 4? See analysis 6) (Why is Y equal to 2? See analysis 4), so F2 = 10.

After calculating the F2 value, return to text1.text = F2 (4, Y) and execute it. Because F2 = 10 (why is it 10? See Analysis 7), that is, text1.text = 10, so the text box control displays 10.

Analyze the program execution result of text2.text = F1 (x) by yourself. I have already explained the key points in detail, so they can be accurate. if you still don't understand it, you should take a good look at the book.

How to define VB Function Parameters

I. Definition and call of sub-Processes

1. Types of sub-Processes

(1) In VB, there are two sub-processes: event process and general process.

Event Process

An event process is a code block executed in response to an event. The event process is generally created by VB and cannot be added or deleted by users. The default current event process is private. The event process is appended to forms and controls. Its Control event syntax is:

Private sub <Control name >_< event name> ([parameter table])

[(Statement group)]

End sub

General Process

A common process is a code block that must be displayed and called by other processes. The general process is created by the user. In a process, a common process can be called by other processes, which improves the code utilization. The general process is divided into sub-process and function process.

(2) define a general process

A general process generally completes a specified task. A general process is not associated with any specific event and can only be called by other processes. It can be stored in a form or standard module.

The sub-process format is as follows:

[Static] [public | private] sub process name ([parameter table])

Definition of local variables or constants

Statement Block

[Exit sub]

Statement Block

End sub

Note: Sub-processes can be placed in the standard module, class module, and form module. By default, sub-processes in all modules are public, which means that they can be called everywhere in the application; if private is selected, only the program in the module where the process is located can call the process.

If the static keyword is used, the storage space of all local variables in the process is allocated only once, and the value of this variable exists throughout the program running, that is, the value of each local variable always exists when this process is called. If static is omitted, the stored space is allocated to the variable every time the process is called, when the process ends, the storage space of the variable is released.

The parameter table is similar to a variable declaration. It declares the value passed in from the call process. Specifies the number and type of variables in the transfer process. Each variable is separated by a comma. The format parameter is of the variant data type by default.

One of the purposes of establishing a general process is to reduce repeated code, put the public statement into the exit process (general process), and call it by the event process.

(3) create a new general process

Two methods:

Use the "add process" dialog box

In the code editor window, enter

View Process
View the process in the current Module

View processes in other modules

(4) Call Process

Form: (1) Name of the call subprocess [(real parameter list)]

(2) subprocess name [real parameter list]

Example:

(1) A Window contains three command buttons. When a user clicks one of them, other buttons cannot be used, and the buttons in the window are the same. The processing method is the same, use a process.

(2) Use the design method of subroutine to calculate 5 first! + 6! + 8! Value Program.

Ii. Define and call the function Process

A function is another form of process. When a sub-process returns a value for execution, it is easier to use it as a function. VB contains many built-in or internal functions. When writing a program, you only need to write a function name and specify a parameter to obtain the function value. When a program needs to use a certain formula or call them multiple times, such a function is called a user-defined function. Like internal functions, user-defined functions can be used in programs or function embedding.

Function Process Definition

(1) use the "add process" command in the "Tools" menu to define

(2) Use the code window to directly define

The process of user-defined functions is as follows:

[Static] [public | private] function procedure name ([parameter list]) [as type]

Definition of local variables or constants

Statement Block

Function name = return value

[Exit function]

Statement Block

Function name = return value

End Function

Function process call

Form: Function Procedure name ([parameter list])

Note: The method used to call a function in VB is the same as that used to call any internal function. You can also call the function process as you call the sub process.

For example, if we know the values of the two right corner edges of a triangle, we can calculate the function of the third side (oblique side.

Function nuse (A as interger, B as interger) as single

Nuse = sqr (a ^ 2 + B ^ 2)

End Function

Method for calling function in VB: strx = nuse (width, height)

You can also use the following statement to call the same function process: Call nuse () or nuse.

Example:

(1) Design a user-defined function for calculating the circular area.

(2) a function that calculates the rectangular area based on the known length and width.

(3) Calculate the factorial function of any integer N, and then calculate the sum of the factorial between 3 and 10.

Note: differences between functions and processes

A function starts with a function and a process starts with a sub.

You can use a function when the process returns a value. When a process has multiple return values, it is used.

A function returns a result value through the function name. The type of the function (result) must be described after the form parameter table of the function. The results of the process are sent back by parameters.

The function body must include at least one statement that assigns a value to the function. The process name cannot be assigned a value.

Function calls appear in expressions. The call of the process must be used as a separate statement.

The parameter does not have a specific value. It only represents the number, position, and type of the parameter. It can only be a simple variable, not a constant, array element, or expression.

Iii. parameter transfer

In the process of calling a parameter, the first step is "form-to-reality combination", that is, passing by value or by address, implement data transmission between the calling program and the called process. By passing parameters, sub or function processes can execute the same type of tasks according to different variables. For convenience, the formal parameters are abbreviated as form parameters, and the actual parameters are abbreviated as real parameters.

In Visual Basic, there are two ways to pass parameters: pass by value and pass by address ). When passing parameters by value, only a copy of The Real Variable is passed. If the parameter value is changed during the adjustment process, only the copy is affected, but the real variable itself is not affected. That is, when the control returns the calling program, the real variable remains unchanged before the call. During the definition process, if no keyword "byval" exists before the parameter name, that is, the default modifier before the parameter name, or the keyword "byref" exists, the parameter is specified as an address-based parameter. When passing parameters by address, the address of the real variable (simple variable, array element, array to record, etc.) is transferred to the called process. Therefore, the addresses of the parameters are the same as those of the combined parameters. That is to say, the parameters share the same "Address" of the memory, that is, the same storage unit. In this way, once the formal parameter value is changed, the corresponding real parameter value also changes.

Formal parameters and actual parameters

A formal parameter is a variable that appears in a sub or function statement when a common process is defined. It is a variable that receives a sub-process. Each variable in the form parameter table is separated by a comma. A real parameter is a constant, variable, or expression transmitted to a sub or function when a sub or function is called. The real parameter table can be composed of constants, expressions, valid variable names, and array names. Parameters in the real parameter table are separated by commas.

Pass by value and by address

There are two ways to pass parameters: if the actual parameter in the call statement is a constant or expression, or the byvall keyword is used during the definition process, the parameter can be passed by value. If the actual parameter in the call statement is a variable or the byref keyword is used during the definition process, it can be passed by address. Otherwise, parameters are passed by address by default.

(1) passing parameters by value

When parameters are passed by address, only copies of the variables are passed. If the process changes this value, the variable will only affect the copy, but will not affect the variable itself. When a variable is required to be transferred by value, you can first convert the variable into an expression. The simplest way to convert the variable into an expression is to put it in parentheses. Or when defining the process, use the byval keyword to indicate that the parameter is passed by value. Example: sub post (byval num as integer)

For example, run the following program to understand the passing parameters by value.

Private Sub Form_Click( )     Dim a as intger, b as integer, c as integer     A=5: b=3 : c=9ClsPrint a; b; cCall prod( (a), (b), (c) )Print a; b; cEnd     SubSub prod (a as intger, b as integer, c as integer )     Print a; b; ca=6 : b=8 : c=a*b     print a; b; c

(2) PASS Parameters by address

Passing parameters by address means that the process accesses the content of the actual Variable Based on the memory address of the variable, that is, the format parameter uses the same memory address unit as the actual parameter, in this way, the value of the variable itself can be changed through the sub-process. By default, parameters are transmitted by address. When transferring a call, the actual parameter must be a variable, and a constant or expression cannot be transferred.

For example, run the following program to understand the parameters passed by address.

Private Sub Form_Click( )     Dim a as intger, b as integer, c as integer     A=5: b=3 : c=9ClsPrint a; b; cCall prod( a, b, c )Print a; b; cEnd SubSub prod (x as intger, y as integer, z as integer )     Print x; y; zx=6 : y=8 : z=x*y     print x; y; z

Example:

Private sub form_click () dim X as intger, y as integer x = 8: Y = 3 call test (5, X, Y + 1) '5 transfer value, x transfer address, Y + 1 print "main program", 5, X, yend subsub test (A as intger, B as integer, C as integer) print "subroutine", A, B, c A = 2: B = 4: c = 9end sub

Iv. Process nesting and recursive calling

1. Process nesting

2. recursive call of the process

Recursive call refers to a process that calls itself directly or indirectly, that is, itself. The VB Process has the recursive calling function. recursive calling is particularly effective in processing factorial operations, Series operations, and power exponent operations.

Recursion is a very useful programming technology. Many mathematical models and algorithm design methods are inherently recursive. It is easier to describe them using recursive procedures than non-recursive methods, which is easier to read and understand, and prove the correctness of algorithms. Therefore, readers should master the recursive programming method. The recursive process is the process of calling (or indirect calling) the process in the process definition. In recursive calls, a certain step of a process must use the results of the previous or previous steps.

V. Scope of Variables
 
Scope definition method

Local variable
Dim, static
Module-level variables dim and private

Global Variables
Public
 

Variable definition location
 
In Process
 
The Declaration section of the module
 
The Declaration section of the module
 

Can it be accessed by other processes in this module?
 
×
 

 

 

Can it be accessed by other modules?
 
×
 
×
 

 

Variable names can be the same if they have different scopes. The range of variables can also be cross. Generally, when the variable names are the same and the scope is different, variables with large limitations will always use "shadow" to cover variables with small limitations (that is, variables with large limitations ). For example, if the program has a module-level variable temp and a process-level variable named temp, its "shadow" will cover the module-level variable temp.

In a process, the variables defined using dim statements are local variables. The value of the variables can be accessed or changed only when they are defined. Such variables become local variables; to enable a variable to be used in all processes of the entire module, the variables defined by the private or dim statement in the (general) and (Declaration) Sections of the module are module-level variables, in this module, you can read and write module-level variables in any process. In the (general) and (Declaration) Sections of the module, variables defined using public statements are global variables, global variables can be read and written in any part of the application.

Dim variables defined in the process cannot be saved after the process ends. When each process is re-executed, the variable content is cleared. If you want to save the value of local variables in the process after leaving the process, you should use the static keyword to define local variables in the process, even if the process ends, the variable value is retained.

The form module, standard module, and class module of the Visual BASIC program can define variables, and also can define variables in processes and functions. Variables defined in different parts have different applicability in the program. Variables in Visual Basic can be divided into local variables (process-level variables), module-level variables, and global variables.

Process-level variables

When a variable is declared in a process, only the code in the process can access or change the value of the variable. The scope of a process variable is limited to this process. Use the dim or static keyword to declare variables within the process.

If a variable is directly used without instructions during the process, the variable is also treated as a process-level variable. Variables described by static always exist throughout the entire running process of the application, while variables described by dim only exist during execution. After exiting the process, such variables will disappear. Process variables are usually used to save temporary data.

1. Process-level variables

The variables declared in the module are module-level variables. There are two types of module-level variables: private and public.

(1) Private module Variables

Private module-level variables can be used in all processes of the entire module, but cannot be accessed by other modules. The method is to use the private or dim keyword to declare a variable in the module declaration.

(2) Public module-level variables

Public module-level variables can be used in all processes of all modules. It applies to the entire application, so public module-level variables are global variables. The description is to use the public keyword declaration in the module declaration.

Full-process variables are memory variables that can be used in all programs (including the main program and process. A full-process variable is like a variable defined in a process. It can be changed and called in a sub-process. After a sub-process is executed, its value is returned to the main program.

2. Survival of Variables

(1) dynamic variables

Dynamic variables are the memory units allocated only when the program runs and enters the subroutine where the variable is located. After processing and exiting the process, the memory units occupied by the variable are automatically released and the value disappears, its memory can be occupied by other variables.

When the dim keyword is used to declare a local variable in the process, the value of the variable is not retained after the process is executed. During each re-execution process, the variable is re-declared. The variables declared with dim are dynamic variables.

(2) static variables

A static variable is the subroutine where the program runs and enters the variable. After the variable value is modified, the program exits and its value is retained. That is, the memory units occupied by the variable are not released. After entering this subroutine again, the original variable value can be used.

Local variables declared during the process using the static keyword are static variables. Static variables can still keep their original values after exiting the process.

 
 

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.