有没有一种方法可以将vba宏代码添加到Excel中?

6
我有一个现有的宏函数问题,所以我需要将宏传递给Excel,也就是添加函数(例如:a())到Excel中,并运行添加的函数("a()")。
注意:我已经知道了要添加宏的Excel路径。请确保回答清晰明了。
如何操作?
提前感谢您的帮助。

我有一个关于Access的类似问题。Excel的工作方式几乎相同,只是您可以直接访问VBProject _Workbook对象,您应该能够在此处获得所需内容:https://dev59.com/e2nWa4cB1Zd3GeqP5e7y 我在答案下面写出了我使用的代码。 - Middas
@Middas:感谢您的回答。我该如何将我的宏函数添加到现有模块中? - user2002774
1个回答

10
  • 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;
                }
            }
        }
    }
    

我们能不能只添加宏,而不安装 PIA 和其他东西?我认为这很繁琐,而且我不确定是否需要在服务器上安装相同的东西。 - user2002774
1
如果您想从C#向Excel文件添加宏代码,则必须为您的Office版本安装主要Interop程序集可再分发版本。请参见此处:http://www.microsoft.com/en-us/download/details.aspx?id=3508。之后,在您的C#项目中添加对Microsoft.Office.Interop.Excel和Microsoft.VBE.Interop的引用。您理解了吗?我的英语很差 :-). - Daniel Dušek
丹尼尔:不,你的英语非常好。你的意思是我必须手动下载这些吗? - user2002774
我收到了错误信息:“System.Runtime.InteropServices.COMException (0x800A03EC):不信任对 Visual Basic 项目的编程访问”。 - hienbt88
@hienbuithanh88 请阅读此文 - Daniel Dušek
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接