【问题标题】:Run a Macro from C# [duplicate]从 C# 运行宏
【发布时间】:2016-12-24 04:19:27
【问题描述】:

我知道您可以使用 Microsoft.Office.Interop.Excel; 在 C# 程序中使用 VBA 命令。

我有接近 10,000 行代码的 VBA,将其转换为 C# 兼容命令是不现实的。它创建一个工作簿并执行数据操作和格式化以根据用户请求打印。

有没有办法将宏存储在 C# 中并创建一个工作簿,然后我可以按原样运行宏?

【问题讨论】:

标签: c# excel vba


【解决方案1】:

您可以像在 Excel 中一样运行宏。 看看这个:

Running an Excel Macro via C#: Run a macro from one workbook on another?

http://oakdome.com/programming/CSharp_RunExcelMacro.php

如果您不希望 Excel 在执行期间可见,请将 Excel.ApplicationClass 的 Visible 属性设置为 false。

【讨论】:

  • 这会运行一个外部文件。我想避免这种情况,b/c 这意味着应用程序必须知道文件在每个用户 PC 上的位置。
  • 您可以拥有一个标准模型的 Excel 文件,并运行宏。在运行时,您可以克隆模型并导入或以编程方式为克隆创建数据,然后运行宏。
【解决方案2】:

这是此解决方案的示例。我创建了工作簿 HelloWorldVBACodeExample.xlsm。然后在这个工作簿 Module1 和 VBA 代码中:

Sub HelloWorld(word)

  MsgBox "Hello world and " & word

End Sub

然后使用 C# 代码创建控制台应用程序:

using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
using System;
using System.IO;

namespace ConsoleAppCallVBA
{
    class Program
    {
    static void Main(string[] args)
    {

        string errorMessage = string.

        #region Check is Excel is installed in the PC on which program is executed

        _Application excel = new _Excel.Application();
        if (excel == null)
        {

            errorMessage = "EXCEL could not be started." + "\n" +
                "This program is able to form reports only on PC with installed Excel. " + "\n" +
                "Check that your office installation is correct.";
            Console.WriteLine(errorMessage);
        }

        #endregion

        excel.Visible = true;

        string fileName = "HelloWorldVBACodeExample.xlsm";
        string pathToExcelXlsmFile = Path.Combine(path, fileName);

        Workbook wb;
        Worksheet ws;
        int sheetNumber = 1;
        wb = excel.Workbooks.Open(pathToExcelXlsmFile);
        ws = wb.Worksheets[sheetNumber];

        //Call VBA code
        excel.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, excel, new Object[] { "HelloWorldVBACodeExample.xlsm!HelloWorld", "My Name"});


        #region Close excel object - release memory from this application

        excel.Quit();
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel);

        #endregion
        }
     }
 }

在执行期间,此 C# 代码执行 VBA 代码并显示在消息框文本“Helo world and My Name”中。在使用此代码 sn-p 的情况下,必须为字符串变量路径分配正确的目录路径,该目录将是带有 VBA 代码的 xlsm 文件。

【讨论】:

    【解决方案3】:

    您必须将 msoAutomationSecurity 启用为低,并将宏作为字符串执行。但是,您可能希望在使用完电子表格后将安全设置重置为高。

    这是一个例子:

        public void ExecuteExcelMacro(string sourceFile)
        {
            ExcelApp.Application ExcelApp = new ExcelApp.Application();
            ExcelApp.DisplayAlerts = false;
            ExcelApp.Visible = false;
            ExcelApp.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityLow;
            ExcelApp.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(sourceFile);
    
            string macro = "Sheet1.SendEmailToUser";
    
            try
            {
                ExcelApp.Run(macro);
                Console.WriteLine("Macro: " + macro + " exceuted successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to Run Macro: " + macro + " Exception: " + ex.Message);
            }
    
            ExcelWorkBook.Close(false);
            ExcelApp.Quit();
            if (ExcelWorkBook != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelWorkBook); }
            if (ExcelApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp); }
        }
    

    【讨论】:

      【解决方案4】:
          public void ExecuteMacro()
          {
              string path = Environment.CurrentDirectory;
              string filePath = "";
              string[] fileEntries = Directory.GetFiles(".\\Source");
              foreach (string fileName in fileEntries)
              {
                  if (fileName.IndexOf(".xlsm") > 0 && fileName.IndexOf("$")<1) filePath = fileName;
              }
      
              if (filePath == "") return;
      
              filePath = filePath.Replace(".\\", "\\");
              string fileDest = filePath.Replace("Source","Processed");
              filePath = path+filePath;
              fileDest = path+fileDest;
      
              Excel.Application ExcelApp = new Excel.Application();
              Excel.Workbook wb = ExcelApp.Workbooks.Open(filePath, ReadOnly: false);
      
              try
              {
                  ExcelApp.Visible = false;
                  ExcelApp.Run("UpdateSheets");
      
                  try
                  {
                      File.Delete(fileDest);
                  }
                  catch (Exception) { }
      
                  wb.SaveAs(fileDest);
              }
              catch (Exception) { }
      
              wb.Close(false);
              ExcelApp.Application.Quit();
              ExcelApp.Quit();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 2015-10-20
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-17
        相关资源
        最近更新 更多