4

I am creating workbooks from a template. The template already has the required code modules in it. I am trying to get a reference to one of the code modules, the one that the code needs to be imported to (the code is always different so having a .bas file wont work here as there would be hundreds of them).

I can easily access a new code module using

var codeModule = excelWorkbook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);

But I need to access the existing "Methods" code module in the instantiated workbook variable

 //initialize the Excel application and make it invisible to the user.
        var excelApp = new Excel.Application
        {
            UserControl = false,
            Visible = false
        };

        //Create the Excel workbook and worksheet - and give the worksheet a name.
        var excelWorkbook = excelApp.Workbooks.Open(TemplateFilePath);
        excelWorkbook.Author = Acknowledgements.Author;
        var bookPath = excelWorkbook.Path;

        //add the macro code to the excel workbook here in the Methods module.
       //this adds a new module, how do I access an existing one?
        var codeModule = excelWorkbook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);

I could just loop through the modules and get it by testing name equality but there must be a way to retrieve it in one line of code.

1 Answer 1

4

Use the Item method of the VBComponents collection to retrieve an existing VBComponent by name or numeric index:

using VBIDE = Microsoft.Vbe.Interop;

VBIDE.VBComponent component = excelWorkbook.VBProject.VBComponents.Item("Methods");
VBIDE.CodeModule module = component.CodeModule;
Sign up to request clarification or add additional context in comments.

3 Comments

Just figured that out and tested. Thank you for confirming
Where does the VBIDE come from? Apparently it is not part of Microsoft.VBE.Interop or Microsoft.Office.Interop.Excel?
@ScottinTexas: I don't remember exactly where. Microsoft.Vbe.Interop shows up as VBIDE in Solution Explorer, but there's no VBIDE namespace. Maybe I had added using VBIDE = Microsoft.Vbe.Interop;

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.