2

Is it possible to write a WPF C# application that can load and read a VBA Macro from a separate text file, open an existing Excel workbook, and process the VBA macro against it?

I am NOT trying to convert VBA to C# or generate VBA from C#. The application, VBA Macro text file (the VBA is extracted and saved separately on a text file), and Excel are all written / generated separately by different people.

The application load and read a text file that contains VBA, and open an existing excel file and run the Macro against it either by injecting the macro to excel or even better, leave the workbook without a macro in it.

I have no idea how or where to start, or if that is even possible. The closet I found on SO is Injecting vba macro code into excel using .net but doesn't seem to help. I'm looking for any suggestion to get me start and I'll share and update my progress here.

1
  • You could put your VBA into an excel workbook or addin, then load it into excel and call the routine(s) you need to run. Commented Sep 27, 2011 at 14:57

1 Answer 1

3

Here is the way to add some VBA from file in VBA (shouldn't be so hard to adapt it to C# but I am not familiar enough to C# syntax):

Function Insert_VBACode(ByRef oWB As Workbook)
    Dim oVBP As VBProject   ' VB Project Object
    Dim oVBC As VBComponent ' VB Component Object
    On Error GoTo Err_VBP
    Set oVBP = oWB.VBProject
    Set oVBC = oVBP.VBComponents.Add(vbext_ct_StdModule)
    oVBC.CodeModule.AddFromFile "c:\VBADUD\Templates\MSample.bas"
    oWB.Application.Run "'" & oWB.name & "'!SayHello"
    oWB.Save
End Function

[Source] (have a look there if you want to add any error handling I've removed here for more readability).
You can also open the workbook instead of taking it as an argument of the function.

And then, you can call your imported macro from C# thanks to this walkthrough from MSDN.

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.