zoukankan      html  css  js  c++  java
  • C#调用Excel宏

    using System;
    using Excel = Microsoft.Office.Interop.Excel;
    
    namespace WindowsFormsApplication1
    {
        /// <summary>
        /// 执行Excel VBA宏帮助类
        /// </summary>
        public class ExcelMacroHelper
        {
            /// <summary>
            /// 执行Excel中的宏
            /// </summary>
            /// <param name="excelFilePath">Excel文件路径</param>
            /// <param name="macroName">宏名称</param>
            /// <param name="parameters">宏参数组</param>
            /// <param name="rtnValue">宏返回值</param>
            public void RunExcelMacro(Excel.Application app, string macroName, object[] parameters, out object rtnValue)
            {
                // 根据参数组是否为空,准备参数组对象
                object[] paraObjects;
                if (parameters == null)
                    paraObjects = new object[] { macroName };
                else
                {
                    int paraLength = parameters.Length;
                    paraObjects = new object[paraLength + 1];
                    paraObjects[0] = macroName;
                    for (int i = 0; i < paraLength; i++)
                        paraObjects[i + 1] = parameters[i];
                }
                rtnValue = this.RunMacro(app, paraObjects);
            }
    
            /// <summary>
            /// 执行宏
            /// </summary>
            /// <param name="oApp">Excel对象</param>
            /// <param name="oRunArgs">参数(第一个参数为指定宏名称,后面为指定宏的参数值)</param>
            /// <returns>宏返回值</returns>
            private object RunMacro(object app, object[] oRunArgs)
            {
                object objRtn;     // 声明一个返回对象
    
                // 反射方式执行宏
                objRtn = app.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, app, oRunArgs);
    
                return objRtn;
            }
        }
    }


    使用方法

    app = new Microsoft.Office.Interop.Excel.Application();
    app.Visible = true;
    
    string filePath = @"F:	est.xlsm";
    Workbook wb = app.Workbooks.Open(filePath);
    
    object objRtn = new object();
    
    // 执行指定Excel中的宏,执行时显示Excel
    ExcelMacroHelper excelMacroHelper = new ExcelMacroHelper();     
    excelMacroHelper.RunExcelMacro(app,"hong",new Object[] { "现在时刻" },out objRtn);
    
    MessageBox.Show(objRtn.ToString());


    在Excel中新增“模块”

    Function hong(title As String)
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Worksheets("Sheet1")
        ws.Cells(1, 1).Value = title & ",123"
        hong = title & ",123"
    End Function
  • 相关阅读:
    程序的本质复杂性和元语言抽象
    编译器词法消歧设计
    关于分工的思考 (Thoughts on Division of Labor)
    数据即代码
    类型的本质和函数式实现
    二叉树迭代器算法
    kvm虚拟化存储管理
    kvm网络虚拟化管理
    kvm虚拟机的四种网络模式
    Linux 中交换空间 (swap)应该分多大才好?
  • 原文地址:https://www.cnblogs.com/timy/p/3490294.html
Copyright © 2011-2022 走看看