Declare Public Variable

confusion123

Active Member
Joined
Jul 27, 2014
Messages
400
If you declared a variable within a standard module with Dim, that variable is only available within that module.

If you declared it at the top of the standard module, it's available throughout that module but not outside it.

If you declared a variable in a standard module at the top with Public, it is available throughout the entire workbook.

But if you declared a variable as Public in a Class Module (or worksheet or userform), is it still available throughout the entire workbook?

If so, what's the difference between declaring Public MyVar in a standard module v a class module (or worksheet or userform)?

Thanks
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
A Class module creates a custom object.

The Public declaration in a Class module essentially creates a Public property of that object.

If you a Class Module named Class1

Code:
' in code module for Class1

Public Name As String

You would be able to refer the Name of each instance of Class1.

Code:
'in normal module

Sub Test()
    Dim oneThing as New Class1
    Dim twoThing as New Class1

    oneThing.Name = "Bob"
    twoThing.Name = "Sally"

    MsgBox oneThing.Name & " and " & twoThing.Name & " are " & IIF(oneThing.Name = twoThing.Name, "the same.", "different.")
End Sub

I don't think of them a variables, but as features of the custom object created by the Class module.
 
Upvote 0

Forum statistics

Threads
1,213,501
Messages
6,114,010
Members
448,543
Latest member
MartinLarkin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top