Sei sulla pagina 1di 2

Opening the Visual Basic Editor

Press Alt + F11


or
Developer Tab --> View Code

How to add Developer Tab to the ribbon?


File Tab ->
Options ->
Customize Ribbon ->
Tick on the checkbox for developer ->
OK

Declaring Variables
In VBA, variable declarations are not mandetory.
If a variable is used without being declared, or if no type is specified,
it will be assigned the type Variant.

Dim x
x=10
y=20

Here x and y becomes Variant type variables because x is declared without


any type and y is not declared at all.

A Variant type variable may be assigned values of any type.

x = "Hello"
y = "Good morning"

Option Explicit
Use the Option Explicit statement on first line of a module to
force all variables to be declared before usage.

Dim statement
To explicitly declare variables in VBA, use the Dim statement,
followed by the variable name and type.

Multiple variables can be declared on a single line using commas


as delimiters, but each type must be declared individually, or
they will default to the Variant type.

Dim x1 As String, x2, x3 As Integer, x4 As Long

Here x1 becomes a String type variable,


x2 becomes a Variant type variable,
x3 becomes a Integertype variable,
x4 becomes a Long type variable.

Variables can also be declared using Data Type Character suffixes


($ % & ! # @), however using these are increasingly discouraged.

Dim this$ 'String


Dim this% 'Integer
Dim this& 'Long
Dim this! 'Single
Dim this# 'Double
Dim this@ 'Currency
Other ways of declaring variables are:
Using Static keyword:
Static x as Integer

When you use the Static statement instead of a Dim statement,


the declared variable will retain its value between calls.

Using Public keywords:


Public x as Integer

Public variables can be used in any procedures in the project.


If a public variable is declared in a standard module or a
class module, it can also be used in any projects that
reference the project where the public variable is declared.

Using Private keywod:


Private x as Integer

Private variables can be used only by procedures in the


same module.

Potrebbero piacerti anche