Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Excel VBA code and button programmatically from C#

Tags:

c#

export

excel

vba

I am in the middle of simple method, that saves my DataGridView into an Excel document (1 sheet only) and also adds VBA code and a button to run the VBA code.

public void SaveFile(string filePath)
    {

        Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
        ExcelApp.Application.Workbooks.Add(Type.Missing);

        //Change  Workbook-properties.
        ExcelApp.Columns.ColumnWidth = 20;

        // Storing header part in Excel.
        for (int i = 1; i < gridData.Columns.Count + 1; i++)
        {
            ExcelApp.Cells[1, i] = gridData.Columns[i - 1].HeaderText;
        }

        //Storing Each row and column value to excel sheet
        for (int row = 0; row < gridData.Rows.Count; row++)
        {
            gridData.Rows[row].Cells[0].Value = "Makro";
            for (int column = 0; column < gridData.Columns.Count; column++)
            {
                ExcelApp.Cells[row + 2, column + 1] = gridData.Rows[row].Cells[column].Value.ToString();
            }
        }

        ExcelApp.ActiveWorkbook.SaveCopyAs(filePath);
        ExcelApp.ActiveWorkbook.Saved = true;
        ExcelApp.Quit();
    }

I only implemented DataGridView export.

EDIT: Thanks to Joel I could, with proper words, search again for the solution. I think that this may be helpful. Would you correct me or give a tip or two about what I should look for.

like image 326
1GurU9 Avatar asked Jun 26 '12 18:06

1GurU9


People also ask

How do I add a button programmatically in VBA?

Go to Tools-Macro-Macros or simply press Alt + F8. Choose "AddButtonAndCode" and then choose "Execute" or simply double-click "AddButtonAndCode". A new button will appear and if you click it you will see a message box, telling you which button you have clicked (in case you have more than one).

Can I use C# in VBA?

You can expose code in a Visual C# project to Visual Basic for Applications (VBA) code if you want the two types of code to interact with each other. The Visual C# process is different from the Visual Basic process.


1 Answers

I just wrote a small example which adds a new button to an existing workbook and afterwards add a macro which will be called when the button is clicked.

using Excel = Microsoft.Office.Interop.Excel;
using VBIDE = Microsoft.Vbe.Interop;
...

private static void excelAddButtonWithVBA()
{
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE");
    Excel.Worksheet wrkSheet = xlBook.Worksheets[1];
    Excel.Range range;

    try
    {
        //set range for insert cell
        range = wrkSheet.get_Range("A1:A1");

        //insert the dropdown into the cell
        Excel.Buttons xlButtons = wrkSheet.Buttons();
        Excel.Button xlButton = xlButtons.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height);

        //set the name of the new button
        xlButton.Name = "btnDoSomething";
        xlButton.Text = "Click me!";
        xlButton.OnAction = "btnDoSomething_Click";

        buttonMacro(xlButton.Name, xlApp, xlBook, wrkSheet);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    xlApp.Visible = true;
}

And here we got the buttonMacro(..) method

private static void buttonMacro(string buttonName, Excel.Application xlApp, Excel.Workbook wrkBook, Excel.Worksheet wrkSheet)
{
    StringBuilder sb;
    VBIDE.VBComponent xlModule;
    VBIDE.VBProject prj;

    prj = wrkBook.VBProject;
    sb = new StringBuilder();

    // build string with module code
    sb.Append("Sub " + buttonName + "_Click()" + "\n");
    sb.Append("\t" + "msgbox \"" + buttonName + "\"\n"); // add your custom vba code here
    sb.Append("End Sub");

    // set an object for the new module to create
    xlModule = wrkBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);

    // add the macro to the spreadsheet
    xlModule.CodeModule.AddFromString(sb.ToString());
}

Found this information within an KB article How To Create an Excel Macro by Using Automation from Visual C# .NET

like image 114
Pilgerstorfer Franz Avatar answered Nov 14 '22 23:11

Pilgerstorfer Franz