using System;
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
static void Main(string[] args)
{
// 创建 Excel 应用程序对象
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true; // 设置为 true 以显示 Excel 窗口
try
{
// 打开工作簿
Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\workbook.xlsx");
// 将 VBA 代码写入工作簿
string vbaCode = @"
Sub HelloWorld()
MsgBox ""Hello, World!""
End Sub
";
AddVbaModule(workbook, vbaCode);
// 执行 VBA 宏
excelApp.Run("HelloWorld");
// 保存并关闭工作簿
workbook.Save();
workbook.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
// 退出 Excel 应用程序
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
// 将 VBA 代码添加到工作簿的模块中
static void AddVbaModule(Excel.Workbook workbook, string vbaCode)
{
// 获取 VBA 项目
Microsoft.Vbe.Interop.VBProject vbProject = workbook.VBProject;
// 添加一个新模块
Microsoft.Vbe.Interop.VBComponent vbComponent = vbProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule);
// 将 VBA 代码写入模块
vbComponent.CodeModule.AddFromString(vbaCode);
}
}
02-20
11-23
1101
