How do I declare a global variable in VBA? How do I declare a global variable in VBA? vba vba

How do I declare a global variable in VBA?


You need to declare the variables outside the function:

Public iRaw As IntegerPublic iColumn As IntegerFunction find_results_idle()    iRaw = 1    iColumn = 1


This is a question about scope.

If you only want the variables to last the lifetime of the function, use Dim (short for Dimension) inside the function or sub to declare the variables:

Function AddSomeNumbers() As Integer    Dim intA As Integer    Dim intB As Integer    intA = 2    intB = 3    AddSomeNumbers = intA + intBEnd Function'intA and intB are no longer available since the function ended

A global variable (as SLaks pointed out) is declared outside of the function using the Public keyword. This variable will be available during the life of your running application. In the case of Excel, this means the variables will be available as long as that particular Excel workbook is open.

Public intA As IntegerPrivate intB As IntegerFunction AddSomeNumbers() As Integer    intA = 2    intB = 3    AddSomeNumbers = intA + intBEnd Function'intA and intB are still both available.  However, because intA is public,  ''it can also be referenced from code in other modules. Because intB is private,''it will be hidden from other modules.

You can also have variables that are only accessible within a particular module (or class) by declaring them with the Private keyword.

If you're building a big application and feel a need to use global variables, I would recommend creating a separate module just for your global variables. This should help you keep track of them in one place.


To use global variables, Insert New Module from VBA Project UI and declare variables using Global

Global iRaw As IntegerGlobal iColumn As Integer