Refering to code in worksheet

dugdugdug

Active Member
Joined
May 11, 2012
Messages
342
Sheet1 is named Graph and contains some code:

Code:
Sub MyWorksheetCode

' just some code

End Sub

In Module1, I have the following:

Code:
Sub MyModuleCode

Dim wks as Worksheet

Set wks = Worksheets("Graph")

' Call wks.MyWorksheetCode <- This does not work

Call Sheet1.MyWorksheetCode

End Sub

Why is it in the above, calling the subroutine using the variable wks does not work?

Thanks
 
Last edited:
That's my point. The generic Worksheet class does not have a MyWorksheetCode method. Your specific Sheet1 class, which inherits from the generic class, does have that method. You can declare the variable as a Variant (as you have) or an Object or as Sheet1:
Code:
Sub MyModuleCode()
' any of these will work
Dim wks as Sheet1
' Dim wks as Object
' Dim wks

Set wks = Worksheets("Graph")
Call wks.MyWorksheetCode
End Sub

You have other answers, but the code I posted worked for me:

Code:
'Sheet1 module
Sub MyWorksheetCode()
    MsgBox "Hello"
End Sub

'General module
Sub MyModuleCode()
    Dim wks As Worksheet
    Set wks = Worksheets("Graph")
    Application.Run wks.CodeName & ".MyWorksheetCode"
End Sub

Thanks both these sound good.
 
Upvote 0

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.

Forum statistics

Threads
1,215,373
Messages
6,124,544
Members
449,169
Latest member
mm424

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