Home

VBA Keywords: Private

 

A Private Variable

A variable is referred to as private if it can be accessed only by code from within the same file (the same module) where it is used. To declare such a variable, instead of Dim, you use the Private keyword. Here is an example:

Option Explicit

Private LastName As String

Sub Exercise()
    Dim FirstName As String
    
    FirstName = "Patricia"
    LastName = "Katts"
End Sub

Remember that a private variable can be accessed by any code in the same module.

A private variable is available inside its module but not outside its module. If you declare a private variable in a module and try accessing it in another module, you would receive an error:

Module 1:

Option Explicit

Private FullName As String

Module 2:

Option Explicit

Private LastName As String
Private FirstName As String

Sub Exercise()
    FirstName = "Patricia"
    LastName = "Katts"
    FullName = FirstName & " " & LastName
    
    ActiveCell.FormulaR1C1 = FullName
End Sub

This would produce:

Error: Variable Not Declared

 
     
 

Home Copyright © 2009-2010 FunctionX, Inc.