Need a better understanding about Public Variables

Pookiemeister

Well-known Member
Joined
Jan 6, 2012
Messages
626
Office Version
  1. 365
  2. 2010
Platform
  1. Windows
I am trying to get a better understanding how to declare Public variables and call them in various subs (mainly Private Subs). I am using the message box to test my code. O.K. so just below the Option Explicit and above a Private Sub, I declared a Public variable.
Code:
Option Explicit


Public mySheet As Worksheet

Private Sub cmdbtnOpen_Click()
    
    Set mySheet = ActiveSheet
    MsgBox mySheet.Name
    
End Sub
The above code works as expected. However the code below displays a Run-time error 424 Object Required.
Code:
Private Sub cmdbtnDone_Click()


    MsgBox mySheet.Name
    
    
End Sub
Is it because I didn't do the following code before my message box.
Code:
Set mySheet = ActiveSheet

Or should I of just created a Public Sub that displays the following inside a module and called it.
Code:
Public Sub Messagebox()
    Set mySheet = ActiveSheet
    MsgBox mySheet.Name
End Sub

Thank You.
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
Is it because I didn't do the following code before my message box.
Code:
Set mySheet = ActiveSheet

You don't have to define MySheet immediately before using it, but you do have to define it at sometime before using it. It could be in another procedure as long as it's before. Otherwise it's just an empty variable with no value.
 
Upvote 0

Forum statistics

Threads
1,224,818
Messages
6,181,152
Members
453,021
Latest member
Justyna P

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