11.3.1 understand visual basic syntax
This section describes the most common syntax elements.
11.3.1.1 syntax of the activate Method
Syntax: object. Activate
In the syntax of the activate method, an object is a placeholder for the provided information. In this example Code Returns an object. For example, the following process activates the second window in the active document.
Sub makeactive ()
Windows (2). Activate
End sub
11.3.1.2 msgbox function syntax
Syntax: msgbox (prompt [, Buttons] [, title] [, helpfile, context])
In the syntax of the msgbox function, the parameters in the brackets are the name parameters of the function. Parameters in square brackets are optional (you do not need to type square brackets in Visual Basic ). In the msgbox function, the only required parameter (prompt) is the text of the prompt.
You can specify the parameters of functions and methods by position or name in the code. If parameters are specified by location, each parameter must be separated by commas (,) based on the order in the syntax. For example:
Msgbox "your answer is correct! ", 0," answer box"
If the parameter is specified by name, the parameter name must be used or followed by the colon and equal sign (: =), and the parameter value must be added. You can specify the name parameters in any order, for example:
Msgbox title: = "answer box", prompt: = "your answer is correct! "
The syntax of functions and some methods will use parentheses to close the parameters. These functions and methods return values. Therefore, you must close the parameters with parentheses to assign values to variables. If the return value is ignored or all parameters are not passed, parentheses are not required. If no value is returned, you do not need to enclose the parameter in parentheses. The preceding rules apply to both named parameters and positional parameters.
In the following example, the return value of the msgbox function is a number, which is stored in the variable myvar to indicate the selected button. Because the return value is required, parentheses must be used for calling. The other message box is used to display the variable value.
Sub question ()
Myvar = msgbox (Prompt: = "I enjoy my job .",_
Title: = "answer box", buttons: = "4 ")
Msgbox myvar
End sub
11.3.1.3 option statement syntax
Syntax: Option compare {binary | text | database}
In the syntax of the Option compare statement, braces and vertical lines indicate mandatory options (do not enter braces in the Visual Basic Statement ). For example, the following statement indicates that in a module, string comparison is based on the order of text sorting, but not case sensitive.
Option compare text
11.3.1.4 dim statement syntax
Syntax: dim varname [([subscripts])] [as type] [, varname [([subscripts])] [as type]...
In the syntax of dim statements, Dim is a necessary keyword. The only necessary element is varname ). For example, the following statements create three variables: myvar, nextvar, and thirdvar. They are automatically declared as variant variables.
Dim myvar, nextvar, thirdvar
The following example declares a string variable. It contains data types, which can save memory and help identify errors from code.
Dim myanswer as string
If several variables are declared in a statement, the Data Type of each variable must be included. If the data type is missing during the declaration, the variable is automatically declared as variant.
Dim X as integer, y as integer, Z as integer
In the following statements, both X and Y are specified as the variant data type, and only Z is specified as the string data type.
Dim X, Y as integer, Z as string
If an array variable is declared, parentheses must be included, but the lower mark is optional. The following statement defines a dynamic array myarray.
Dim myarray ()
11.3.2 use data syntax effectively
Table 11-1 lists the data types supported by VBA and the storage space size and range.
Note:
An array of any data type requires 20 bytes of memory space, and each array dimension occupies 4 bytes, plus the space occupied by the data itself. The memory space occupied by data can be calculated by the number of data elements multiplied by the size of each element. For example, data in a one-dimensional array consisting of four 2-byte integer data elements occupies 8 bytes. These 8 bytes plus an additional 24 bytes make the total memory space required for this array 32 bytes. The variant that contains an array requires 12 more bytes than a single array.
Note:
Use the strconv function to convert string data from one type to another.
Unless otherwise specified, unspecified variables are specified as the variant data type. This data type allows writingProgramIt is easier, but it is not always the most efficient data type.
Other data types must be considered in the following cases:
The program is very large and many variables are used.
The program must be executed as quickly as possible.
Write data directly to a random storage file.
In addition to variant, supported data types include byte, Boolean, integer, long, single, double, currency, decimal, date, object, and string. You can use the dim statement to declare a variable of the specified type. For example:
Dim X as integer
The preceding statement declares that the variable X is an integer in the range of-32,768 ~ In the range of 32,767. If you try to set a value out of this range to X, an error will occur. If you try to assign a score to X, the score is automatically rounded. For example:
X = 32768 'produces an error. X = 5.9 'set X = 6.
11.3.3 naming rules for Visual Basic
When naming procedures, constants, variables, and parameters in the Visual Basic module, you can use the following rules:
The first character must contain English letters.
Spaces, periods (.), and exclamation points (!) cannot be used in the name (!) , Or @, &, $, #, and other characters.
The name cannot exceed 255 characters.
Generally, the name used cannot be the same as the name of the function process, statement, and method of Visual Basic. You must exit with the same name as the keyword of the program language. If the internal language function, statement, or method used conflicts with the specified name, it must be identified explicitly. The name of the associated Type Library is added before the name of the built-in function, statement, or method. For example, if there is a variable named left, you can only use VBA. Left to call the left function.
Duplicate names cannot be used in the same level of range. For example, two variables named age cannot be declared in the same process. However, you can declare a private variable named age and a process-level variable named age in the same module.
Note:
Visual Basic is case-insensitive, but it retains uppercase letters in the statement where the name is declared.
11.3.4 declare variables, constants, and Arrays
11.3.4.1 declare Variables
Generally, dim statements are used to declare variables. A declaration statement can be placed in the process to create a variable at the process level. You can also place the declaration part on the top of the module to create a variable at the module level.
The following example creates the variable strname and specifies it as the string data type. Dim strname as string
If this statement appears in the process, the variable strname can only be used in this process. If the statement appears in the declaration part of the module, the variable strname can be used by all the processes in this module, but cannot be used by different modules in the same project. To make the variable usable by all processes in the project, add the public statement before the variable, as shown in the following example:
Public strname as string
Variables can be declared as one of the following data types: Boolean, byte, integer, long, currency, single, double, date, string (variable-length string), string * length (Fixed Length string), object, or variant. If no data type is specified, the variant data type is assigned to the default value. You can also use the type statement to create a custom type.
Several variables can be declared in a statement. To specify the data type, the Data Type of each variable must be included. In the following statement, the intx, inty, and intz variables are declared as integer types.
Dim intx as integer, inty as integer, intz as integer
In the following statement, the intx and inty variables are declared as variant; only intz is declared as integer.
Dim intx, inty, intz as integer
In a declaration statement, you do not have to provide the data type of the variable. If the data type is omitted, the variable is set to the variant type.
Public Statement: You can use the public statement to Declare Public module-level variables.
Public strname as string
Public variables can be used in any process in the project. If a public variable is declared in a standard module or a class module, it can also be used by any project that references the public variable to the project to which it belongs.
Private statement: You can use private statements to declare private module-level variables.
Private myname as string
Private variables can only be used in the same module.
Note:
At the module level, the dim statement is the same as the private statement. However, using private statements can make it easier to read and interpret code.
Static statement: When the dim statement is replaced by a static statement, the declared variable retains its original value during the call.
Use the option explicit statement: in Visual Basic, a value assignment statement can be used to implicitly declare variables. All implied declared variables are of the variant type, while Variant variables require more memory resources than most other types of variables. If the variable is explicitly declared as the specified data type, the application will be more effective. Explicitly declaring all variables reduces naming conflicts and spelling errors.
If you do not want Visual Basic to generate an implicit declaration, you can place the option explicit statement before all the procedures in the module. This statement requires explicit declaration of all the variables in the module. If the module contains an option explicit statement, a compilation time error occurs when Visual Basic encounters an undefined variable or spelling error.
You can set an option in the Visual BASIC program environment to automatically include the option explicit statement in all new modules.
Note: You must explicitly declare a fixed-size array and a dynamic array.
Declare an object variable for automation: When an application is used to control the object of another application, a reference to the Type Library of other applications should be set. If a reference is set, object variables can be declared based on the type they are most often specified. For example, if you are using Microsoft Word, you can declare a worksheet type variable in Microsoft Word to represent the worksheet object in Microsoft Excel when you make a reference setting for a Microsoft Excel database.
If other applications are used to control Microsoft Access objects, object variables can be declared based on the type they specify most often. You can also use the keyword new to automatically generate a new instance of an object. However, it may be indicated that it is a Microsoft Access Object. For example, when you declare an object variable in Microsoft Visual Basic to represent Microsoft Access form, you must distinguish between Microsoft Access form object and Visual Basic form object. Therefore, the variable declaration statement must contain the name of the Type Library, as shown in the following example:
Dim frmorders as new access. Form
Some applications do not recognize special Microsoft Access object types. If a reference to the Microsoft Access library has been set in these applications, all Microsoft Access Object variables must be declared as the object type. You cannot use the new keyword to create a new instance of this object. The following example shows how to declare a variable to indicate a Microsoft Access Application object. Then the application creates an instance of the Application object.
Dim appaccess as object
Set appaccess = Createobject ("access. application ")
11.3.4.2 declare Constants
If you want to declare a constant, you can use the const statement to declare it and set its value. After the constant declaration, you cannot change it or assign a new value.
In the declaration part, constants can be declared either in the process or at the top of the module. Constants at the module level are private by default. To declare a public module level constant, you can add the public keyword before the const statement. You can also use the public keyword before the const statement to explicitly declare a private constant, which makes it easier for us to read and interpret the code.
The following example declares that a public constant conage is of the integer type and its value is 34.
Public const conage as integer = 34
Constants can be declared as one of the following data types: Boolean, byte, integer, long, currency, single, double, date, string, or variant. Because the constant value is known, you can specify the data type in the const statement. Detailed information about the data type.
Several constants can be declared in a statement. To specify the data type, the Data Type of each constant must be included. In the following statement, constants conage and conwage are declared as integer types.
Const conage as integer = 34, conwage as currency = 35000.
11.3.4.3 declare an array
The array declaration method is the same as other variables. It can be declared using dim, static, private, or public statements. The difference between a scalar variable (non-array) and an array variable is that the size of an array must be specified. If the array size is specified, it is a fixed-size array. If the size of the group can be changed when the program runs, it is a dynamic array.
Whether the array is indexed from 0 or 1 is based on the option base statement. If option base is not specified as 1, the array index starts from 0.
1. Declare an array of fixed sizes
The following Code declares a fixed-size array, which is an integer array of 11 rows multiplied by 11 columns:
Dim myarray (10, 10) as integer
The first parameter represents the row, and the second parameter represents the column.
Like the declaration of other variables, the Data Type of elements in the array is declared as variant unless a data type is specified to the array. The numeric variant element of each array occupies 16 bytes. Each string-type variant element occupies 22 bytes. To make the written code as concise and clear as possible, the declared array should be a data type rather than variant. The following lines of code compare the sizes of several different Arrays:
'Integer array uses 22 bytes (11 elements * 2 bytes ).
Redim myintegerarray (10) as integer
'Double-precision arrays use 88 bytes (11 elements x 8 bytes ).
Redim mydoublearray (10) as double
The 'shape' array must contain at least 176 bytes (11 elements x 16 bytes ).
Redim myvariantarray (10)
'Integer array uses 100*100*2 bytes (20,000 bytes ).
Redim myintegerarray (99, 99) as integer
'Double-precision arrays use 100*100*8 bytes (80,000 bytes ).
Redim mydoublearray (99, 99) as double
'Use a variant array of at least 160,000 bytes (100*100*16 bytes ).
Redim myvariantarray (99, 99)
The maximum value of the array variable is based on the amount of available memory in the operating system used. If the size of the array used exceeds the total available memory in the system, the speed slows down because data must be read and written back from the disk.
2. Declare a dynamic array
If it is declared as a dynamic array, the array size can be changed during code execution. You can use static, dim, private, or public statements to declare an array and leave it empty in parentheses, as shown in the following example.
Dim sngarray () as single
Note:
The redim statement can be used in the process for implicit array declaration. When using the redim statement, be careful not to misspell the array name. Otherwise, the second array is generated even if the module contains the option explicit statement.
For the array range in the process, you can use the redim statement to change its dimension, to define the number of elements and the underlying binding of each dimension. You can use the redim statement to change the dynamic array whenever needed. However, when this action is taken, the values in the array will be lost. To save the original values in the array, you can use the redim preserve statement to expand the array. For example, the following statement expands the vararray into 10 elements, but the current value in the original array does not disappear.
Redim preserve vararray (ubound (vararray) + 10)
Note:
When you use the preserve keyword for a dynamic array, you can only change the upper-layer binding of the last dimension, but not the number of dimensions.
11.3.5 process and call
11.3.5.1 function Process
The function process is a series of Visual Basic statements contained by the function and end function statements. The function process is similar to the sub process, but the function can return a value. The function process can be called by passing parameters, such as constants, variables, or expressions, through the caller process. If a function process has no parameters, its function statement must contain an empty parentheses. A function specifies a value in one or more statements in the process to return the value to the function name.
In the following example, the Celsius function calculates the Celsius Temperature Based on the Fahrenheit temperature. When the main process calls this function, a variable containing the parameter value is passed to this function. The calculation result is returned to the call process and displayed in a message box.
Sub main ()
Temp = application. inputbox (Prompt: = _
"Please enter the temperature in degrees F .",
Type: = 1)
Msgbox "the temperature is" & Celsius (temp )&"
Degrees C ."
End sub
Function Celsius (fdegrees)
Celsius = (fdegrees-32) * 5/9
End Function
11.3.5.2 sub process
A sub process is a series of Visual Basic statements contained by sub and end sub statements. They execute an action but cannot return a value. A sub process can be called by parameters, such as constants, variables, or expressions. If a sub process has no parameters, its sub statement must contain an empty parentheses.
In the following sub process, each row has a comment to explain its role:
'The Declaration process is named getinfo.
'The sub process has no parameters.
Sub getinfo ()
'Declare the string variable named answer
Dim answer as string
'Specify the return value of the inputbox function to answer
Answer = inputbox (Prompt: = "What is your name? ")
'Condition if... then... else statement
If answer = empty then
'Call the msgbox Function
Msgbox prompt: = "You did not enter a name ."
Else
The 'msgbox function is connected to the answer variable.
Msgbox prompt: = "Your name is" & answer
'End the IF... then... else statement
End if
'End the sub process
End sub
11.3.5.3 attribute Process
The attribute process is a series of Visual Basic statements that allow programmers to create and operate custom attributes. The attribute process can be used to create read-only attributes for forms, standard modules, and class modules. It can be used to replace the public variable in the Code. When setting the attribute value, the above action should be executed.
Different from the public variable, some help strings are assigned to custom attributes in the property process of the Object Browser.
When you create an attribute process, it becomes an attribute of the module contained in this process. Visual Basic provides three types of property procedures:
The property let is used to set the attribute value.
Property get is used to return the property value.
Property set is used to set the process of object reference.
The syntax for declaring an attribute is as follows:
[Public | private] [static] property {GET | let | set}
Propertyname _ [(arguments)] [as type]
Statements
End Property
The attribute process is usually used in pairs: property let and property get, while property set and property get. Declaring a single property get process is like declaring a read-only property. When three Property processes are used together, they are only useful for variant variables, because only variant can contain information of one object or other data types. Property set is intended to be used on objects, while property let is not.
The parameters required in the property Process Declaration are as follows:
Property get property get propname (1,..., n) as type
Property let property let propname (1,..., n, n + 1)
Property set property set propname (1,..., n, n + 1)
In the process of having the same name attribute, the same name and data type must be shared between the first and last parameters (1,..., n.
The property get Process Declaration requires one parameter less than the relevant property let and property set declaration. The data type of the property get process must be the same as that of the relevant property let and the last (n + 1) parameter in the property set declaration. For example, if the following property let process is declared, the name and Data Type of the parameter used in the property get Declaration must be the same as that used in the property let process.
Property Let names (intx as integer, inty as integer,
Varz as variant)
'Execution statement.
End Property
Property get names (intx as integer, inty as integer)
As Variant
'Execution statement.
End Property
In the property set declaration, the Data Type of the last parameter must be the object type or variant.
11.3.5.4 call sub and function Processes
When calling a sub process from another process, you must enter the process name and any required parameter values. The call statement is not required, but if it is used, any parameters must be enclosed in parentheses.
You can use sub processes to organize other processes, so you can easily understand and debug them. In the following example, the sub process main passes the parameter value 56 to call the sub process multibeep. After running multibeep, the control returns main, and the main calls the sub process message. The message box is displayed. When you press the "OK" key, the control returns the main message, and then the main statement exits.
Sub main ()
Multibeep 56
Message
End sub
Sub multibeep (numbeeps)
For counter = 1 to numbeeps
BEEP
Next Counter
End sub
Sub Message ()
Msgbox "time to take a break! "
End sub
1. Call the sub process with multiple parameters
The following example shows two different methods to call a sub process with multiple parameters. When housecalc is called for the second time, parameters must be enclosed by brackets because the call statement is used.
Sub main ()
Housecalc 99800,431 00
Call housecalc (380950,495 00)
End sub
Sub housecalc (price as single, wage as Single)
If 2.5 * wage <= 0.8 * price then
Msgbox "you cannot afford this house ."
Else
Msgbox "This house is affordable ."
End if
End sub
Use parentheses when calling the function.
To use the return value of a function, you must specify the function to the variable and enclose the parameter with parentheses. The following example shows:
Answer3 = msgbox ("are you happy with your salary? ", 4," Question 3 ")
If you do not care about the function return value, you can call the function by calling the sub process. As shown in the following example, parentheses can be omitted to list parameters and do not assign the function to variables:
Msgbox "task completed! ", 0," task box"
Note that if parentheses are included in the preceding example, a syntax error occurs.
2. Pass the name parameter
Sub or function statements can use named parameters to pass values to the called process. Parameters can be transmitted by value or by address. Passing by value is only a copy of a parameter. A variable of the same parameter type and content is created in the function. Changes made to parameters in the process body do not affect actual parameters; if the parameter is passed by address, the actual parameter address is passed. All changes to the parameter during the process will affect the actual parameter ". A named parameter is composed of a parameter name followed by a colon (: =) and an equal sign, and then a value is specified for the parameter.
The following example uses Named parameters to call the msgbox function without return values.
Msgbox title: = "task box", prompt: = "task completed! "
The following example calls the msgbox function using the named parameter. Specify the return value to the variable answer3.
Answer3 = msgbox (Title: = "Question 3 ",_
Prompt: = "are you happy with your salary? ", Buttons: = 4)
11.3.5.5 call the attribute Process
Table 11-2 lists the syntax for calling the attribute process.
When calling a property let or property set process, a parameter always appears on the right of the equal sign (=.
When multiple parameters are used to declare a property let or property set process, Visual Basic transmits the right parameter of the call to the last parameter in the property let or propertyset declaration. For example, Figure 11-18 shows the relationship between the parameters in the property procedure call and the parameters in the property let declaration:
In fact, the attribute process and multiple parameters are used only when the attribute array is created.