Read Sub code from a cell

Celticfc

Board Regular
Joined
Feb 28, 2016
Messages
153
I need to write a sub, where the actual code for this sub is stored in a cell.

I.e.

Sheet1 A1 has “Call MasterCode”

How can I write a sub that actually reads the contents of a cell and actions it?

Or I simply need to copy paste the contents of A1 and paste it to the sub etc.

Many thanks in advance.
 

Excel Facts

Select a hidden cell
Somehide hide payroll data in column G? Press F5. Type G1. Enter. Look in formula bar while you arrow down through G.
Excel cells are for values and formulas.
The VB Editor is for VBA code.

That being said, if you have the text for a sub, including the declaration line and the End Sub in A1, this might do what you want

Code:
Sub test()
    Dim strCode As String
    Dim strProcName As String, strModName As String
    strCode = Range("A1").Text
    With ThisWorkbook.VBProject
        With .VBComponents.Add(vbext_ct_StdModule)
            strModName = .Name
            With .CodeModule
                .AddFromString strCode
                strProcName = .ProcOfLine(.CountOfLines - 1, vbext_pk_Proc)
            End With
        End With
        Application.Run strProcName
        .VBComponents.Remove .VBComponents(strModName)
    End With
End Sub
 
Upvote 0
If all you want to do is call a sub that's named in a cell you can use Application.Run.
Code:
Application.Run Range("A1").Value
 
Upvote 0

Forum statistics

Threads
1,224,923
Messages
6,181,785
Members
453,065
Latest member
jfrsanders

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