7

I have a problem with a existing macro function,so what I have to do is to pass a macro to excel I mean add the function(Ex: a()) to excel,and run the function("a()") added.

Note:I have path of the excel where i`ll have to add macro into. Please be clear about the answers.

How to do this??

Thanks in advance.

2
  • I had a similar question regarding Access. Excel works just about the same way except you can acess the VBProject right off of the _Workbook object, you should be able to get what you need here: stackoverflow.com/questions/13020923/… I wrote out the code I used below the answer. Commented Mar 4, 2013 at 7:35
  • @Middas: Thanks for your answer. How can I add my macro function to a existing module? Commented Mar 4, 2013 at 8:22

1 Answer 1

11
  • install Primary Interop Assemblies Redistributable for your office version
  • Add reference to Assemblies -> Extensions ->Microsoft.Office.Interop.Excel and Microsoft.VBE.Interop

    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    using Microsoft.Vbe.Interop;
    using ExcelInterop = Microsoft.Office.Interop.Excel;
    
    namespace WindowsFormsApplication1
    {
        public partial class AddExcelMacro : Form
        {
            public AddExcelMacro()
            {
                InitializeComponent();
                AddMacro();
            }
    
            public void AddMacro()
            {
                try
                {
                    // open excel file 
                    const string excelFile = @"c:\temp\VBA\test.xlsm";
                    var excelApplication = new ExcelInterop.Application { Visible = true };
                    var targetExcelFile = excelApplication.Workbooks.Open(excelFile);
    
                    // add standart module to file
                    var newStandardModule = targetExcelFile.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
                    var codeModule = newStandardModule.CodeModule;
    
                    // add vba code to module
                    var lineNum = codeModule.CountOfLines + 1;
                    var macroName = "Button1_Click";
                    var codeText = "Public Sub " + macroName +"()" + "\r\n";
                    codeText += "  MsgBox \"Hi from Excel\"" + "\r\n";
                    codeText += "End Sub";
    
                    codeModule.InsertLines(lineNum, codeText);
                    targetExcelFile.Save();
    
                    // run the macro
                    var macro = string.Format("{0}!{1}.{2}", targetExcelFile.Name, newStandardModule.Name, macroName);
                    excelApplication.Run(macro);
    
                    excelApplication.Quit();
    
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    throw;
                }
            }
        }
    }
    
Sign up to request clarification or add additional context in comments.

12 Comments

Daniel:Thanks for the answer. I didnt get this point Add reference to Assemblies -> Extensions ->Microsoft.Office.Interop.Excel and Microsoft.VBE.Interop" (second point).
Daniel: Sorry for that,i have accepted the answer. Now please tel me what is it you `ve mentioned. I have installed PIA.
Cant we just add macro,without installing PIAs and other stuffs? I think its hectic,and im not sure if i have to install the same in server too.
If you want to add macro code to excel file from c# you have to install Primary Interop Assemblies Redistributable for your office version. Have a look here: microsoft.com/en-us/download/details.aspx?id=3508. After that add references to Microsoft.Office.Interop.Excel and Microsoft.VBE.Interop in your c# project. Is this understandable to you? My english is bad :-).
Daniel:No,you are totally good wit english. You mean to say i have to download these manually?
|

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.