4

I don't know if I have been using the correct search terms or not when searching for this functionality, but I'm curious, is it possible to dynamically generate macros in excel-vba? If so, what are the possible methods?

Is metaprogramming supported in excel-vba?

5
  • 1
    Yes eg cpearson.com/Excel/vbe.aspx Commented Dec 19, 2016 at 15:59
  • or here stackoverflow.com/questions/13956104/… Commented Dec 19, 2016 at 16:05
  • @Sorceri Forgive my ignorance regarding VBA/C#, on your response, what's the context of the provided C# code? Could that code be executed from within the VBA project? Commented Dec 19, 2016 at 16:18
  • @jab it is a pretty straight forward conversion, see my answer Commented Dec 19, 2016 at 16:21
  • @Sorceri Very straightforward, thanks again! Commented Dec 19, 2016 at 16:36

1 Answer 1

3

Here is the example I provided converted to VBA. You will need to include a reference to Microsoft Visual Basic for Applications Extensibility and enable access to the VBA project module in the trust center settings.

Sub CreateMacro()
Dim vbComp As VBComponent
Dim functionText As String

Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)

functionText = "Function MyTest()" & vbCrLf
functionText = functionText + "MsgBox " & Chr(34) & "Hello World" & Chr(34) & vbCrLf
functionText = functionText + "End Function"

vbComp.CodeModule.AddFromString functionText

End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.