Naming rules for variables and constants in VBA

Source: Internet
Author: User
Tags naming convention
Technorati label: VBA, naming convention, constant, variable

Generally, naming Rules use a lowercase prefix or suffix to specify the type and scope of a variable. The variable itself should use meaningful names to describe what it is or what it is to be done.A multi-character variable name is connected by several words. The first letter of each word is capitalized and no underline is used.. If you have used a variable name template, its format should be as follows:PrefixnounOrPrefixnounverb.

Constant nameIt should also make some sense,The format is "noun" or "noun_verb "..Constant names are in uppercase, and words are separated by underscores (_).. Although there is no technical error in adding a character to a constant name to specify the data type and scope, this is usually not the case. Constants and variables are both symbolic representations of data. In this sense, they are identical. The difference is that variables can change while constants remain unchanged.

Variable names and constant names can contain a maximum of 255 characters. However, names with more than 25 to 30 characters are clumsy. In addition, to get a meaningful name and clearly express the purpose of a variable or constant, 25 or 30 characters should be enough.

1 variable name

The variable name uses a mix of upper and lower cases (noun or nounverb) to specify what the variable is and what it wants to do. The case-insensitive mixed format is used as a description of the variable name. Here, the first letter of each word is capitalized while the other letters are lowercase.

The variable name has two or three character prefixes to specify the Data Type of the variable. For example, the variables declared in the following statement use the prefix to specify the Data Type of the variable:

  1. Dim strrecipientname as string
  2. Dim intitemsprocessed as integer
  3. Dim blncontinueprocessing as Boolean

The prefix of two characters is usually used to specify the type of the Office application object. For example:

  1. Dim xlapp as Excel. Application
  2. Dim olnamespace as outlook. namespace
  3. Dim wdnewdoc as word. Document

Use the "OBJ" prefix when declaring a common or object variable. This prefix should be used even if you want to create a late bound object variable that represents a Microsoft Office application. For example:

  1. Dim objxlapp as object
  2. Dim objwddocument as object
  3. Dim objolmailitem as object

Global variables and module-level variables must be prefixed with a single character to indicate their applicability. The scope of a variable defines the lifetime and visibility of the variable. Both global variables and module-level variables have a permanent lifetime. That is to say, as long as the application is not closed, the variable will always occupy the memory allocated to it. Variables declared in a process are valid only when they are declared. Their lifetime is the execution time of the Process Code. However, if the keyword static is used to declare a variable.

Global variables are prefixed with lowercase "G", AndUse the public statement in the "Declaration" section of the module. ItVisible to all processes in all modules of the application. For example, public gstrpathtodatasource as string is a global variable that contains a string that is the path of the data source used in the application.

Always use the minimum scope of action to define variables as much as possible. You must use global variables only when you cannot find other ways to share the data contained in variables. Global variables make the code hard to understand and maintain. If you are using too many global variables without careful selection, you may need to redesign the code to reduce global variables.

Module-level variables have lowercase "M" prefixes, YesThe "Declaration" section of the module is declared using dim or private statements.. TheyVisible to all processes in the declared Module. For example, dim mrstcustomerrecords as ADODB. recordset is a module-level object variable used for customer record.In the class module, the module-level variables declared using the private statement have the prefix "P _". Common module-level variables in the class module appear as class attributes and should not have any prefix to indicate their data type or scope of action.

Process-level variables are created using dim statements during the process. For example, dim intcurrentmailitem as integer is a process-level variable used as a cyclic counter. In addition, process-level variables can be declared with the static keyword. Even if the process of declaring static variables has ended, static variables still retain their values.Static Process-level variables have lowercase "S" prefixes. For example, static scurtotalsales as currency creates a process-level static variable to save the sum during a calculation of the current sales volume.

The user-defined type variables are declared in the "Declaration" section of the module. All names are capitalized and followed by "_ type ".You can declare a user-defined type as follows:

  1. Type employeeinfo_type
  2. Strfullname as string
  3. Lngemployeeid as long
  4. Datstartdate as date
  5. Strdepartmentcode as string * 4
  6. Cursalary as currency
  7. End type

The "UDT" prefix should be used to declare module-level variables of the employeeinfo_type.. For example,

  1. Dim mudtemployeerecord as employeeinfo_type

The array variable is prefixed with lowercase "a" and is followed by a pair of parentheses if it is not variant. An array is a variable that can contain multiple values. The array variables must be declared using the dim statement. For example, dim alngnum () is an array variable of a long integer. An array is useful when you need to store multiple values of the same type without creating individual variables for them.

The following are examples of variable names that use the aforementioned general naming conventions:

2 constant name
A constant uses a descriptive name consisting of multiple uppercase words. Each word is separated by an underscore. When declaring a constant, you must use the const statement, the constant name, its data type, and its value. For example, the following constants can be declared in the "Declaration" section of the module to provide the path of the data source used by the application:

  1. Public const database_path as string = "C:/solutions/source/appdata. mdb"

Note that if the public keyword is used to declare a constant, the constant can be used in any process of any module in the application. If the public keyword is not used, a constant has only a module-level scope, which means that it can only be used by the process included in the declared module. If a constant is declared in a process, it can only be used for the code in the process, and the lifetime is only for the execution period of the Code in the process.

Prefixes like I, S, G, and m can be very useful in understanding the value and the scope of a constant. For example,Gsnew_lineNew Line character string (G indicates that it is global to entire application and S indicates that this is a string)

The following are examples of constant names that use the aforementioned general naming conventions:

  1. Access_connectstring
  2. Api_max_stringbuffer
  3. SQL _string

Note:If you create public enumeration constants in the class module, you can use different naming rules to distinguish them from other constants.Constants shoshould be prefixed by the scope prefixes m or g for module or global, respectively. A constant is indicated by appending the letter C to the end of the data type or it can have the generic tag con. for examples,Gintcdiscount. G is the scope, intc indicates the datatype and that it is a constant, with the base name of discount.CondiscountNames the same constant, but conveys less information.MdblcpiIndicates module level, double integer constant with the base name pi.

In addition to the constants you declare, Microsoft Visual Basic for Applications (VBA) and each Microsoft Office application contain built-in constants (internal constants) with predefined values ).Internal constants should always be used instead of the values they represent. Like User-Defined constants, the advantage of using internal constants is that they make your code easier to understand. For example, compare the following two groups of code examples. One group uses internal constants, and the other does not use internal constants. Determine whether internal constants can make the code easier to understand.

  1. If msgbox ("proceed now? ", 48 + 512 + 3 + 16384," Continue? ") = 7 then
  2. Docmd. OpenForm "MERs", 0, 1, 3
  3. End if
  4. If msgbox ("proceed now? ", Vbexclamation + vbdefaultbutton3 + _
  5. Vbyesnocancel + vbmsgboxhelpbutton, "Continue? ") = Vbno then
  6. Docmd. OpenForm "MERs", acnormal, acformedit, acdialog
  7. End if

To view the complete list of constants in VBA and each office application, open "Object Browser" and select an appropriate type library from the "Project/library" dialog box, in the search text box, type the corresponding constant prefix and click search on the object browser toolbar ". The following table shows some examples extracted from the complete list of internal constants.

References:

  1. Http://www.excelpx.com/dispbbs.asp? Boardid = 118 & id = 16138
  2. Patricia cardoza, Teresa Hennig, Armen Stein, Graham seach. "Access 2003 VBA programmer's reference", p.809-p.831, Wiley Publishing, Inc. 2004

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.