在excel文件中添加一个宏

时间:2015-09-05 23:52:21

标签: c# excel-vba vba excel

我有以下宏

Sub test()
    Dim xsheet As Worksheet
    For Each xsheet In ThisWorkbook.Worksheets
        xsheet.Select
        With xsheet.UsedRange
            .Value = .Value
        End With
    Next xsheet      
End Sub

有没有办法将它添加到excel文件并使用c#执行?

任何帮助都是最受欢迎的。

1 个答案:

答案 0 :(得分:1)

从此Siddharth Rout

中提取的MSDN issue解决方案

这应该有效:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //~~> Define your Excel Objects
            Excel.Application xlApp = new Excel.Application();

            Excel.Workbook xlWorkBook;

            //~~> Start Excel and open the workbook.
            xlWorkBook = xlApp.Workbooks.Open("E:\\Users\\Siddharth Rout\\Desktop\\book1.xlsm");

            //~~> Run the macros by supplying the necessary arguments
            xlApp.Run("test");

            //~~> Clean-up: Close the workbook
            xlWorkBook.Close(false);

            //~~> Quit the Excel Application
            xlApp.Quit();

            //~~> Clean Up
            releaseObject(xlApp);
            releaseObject(xlWorkBook);
        }

        //~~> Release the objects
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}

如果您的宏有参数,请说:

Sub ShowMsg(msg As String, title As String)
    MsgBox msg, vbInformation, title
End Sub

您必须将xlApp.Run("test");更改为xlApp.Run("ShowMsg", "Hello from C# Client", "Demo to run Excel macros from C#");

相关问题