Skip to content

Instantly share code, notes, and snippets.

@dck-jp
Created June 14, 2014 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dck-jp/15d96e98e7bdb1bfc266 to your computer and use it in GitHub Desktop.
Save dck-jp/15d96e98e7bdb1bfc266 to your computer and use it in GitHub Desktop.
Dynamic Code Generate & Execute@VBA
Option Explicit
Sub Main()
Dim tempModule As Object: Set tempModule = GenerateSub
Application.Run "SubMethod"
ThisWorkbook.VBProject.VBComponents.Remove tempModule
End Sub
Function GenerateSub() As VBComponent
Dim code As String
code = "Sub SubMethod" & vbNewLine & _
vbTab & "MsgBox """ & Time & """" & vbNewLine & _
"End Sub"
Dim tempModule As VBComponent: Set temp = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)
Call tempModule.CodeModule.DeleteLines(1, temp.CodeModule.CountOfLines)
Call tempModule.CodeModule.AddFromString(code)
Set GenerateSub = tempModule
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment