本文指导如何使用 C# 修改 Excel VBA 库。它共享 IDE 设置、步骤列表和代码片段,以使用 C# 在 Excel VBA 代码库中添加模块。它演示了访问 VBA 项目以及在工作簿中添加模块和代码。
使用 C# 修改 Excel VBA 代码库的步骤
- 设置IDE使用Aspose.Cells for .NET添加模块和代码
- 创建一个 workbook,访问一个工作表,然后添加一个 VBA module
- 使用新模块索引访问新创建的模块
- 设置模块的名称和代码
- 使用新的 VBA 宏保存输出 Excel 文件
这些步骤说明了使用 C#* 在 *Excel VBA 源代码库中添加模块的过程。访问所选工作簿的 VbaProject.Modules 集合并调用 Add() 方法添加新模块。在保存生成的 XLSM 文件之前,获取对新创建的模块的引用并将其名称和代码设置为所需的值。
使用 C# 更新 Excel 宏库的代码
using System; | |
using Aspose.Cells; | |
using Aspose.Cells.Vba; | |
class Program | |
{ | |
static void Main(string[] args) // Add VBA code in Excel using C# | |
{ | |
new License().SetLicense("License.lic"); | |
// Create new workbook, access a sheet and add a VBA module | |
Workbook workbook = new Workbook(); | |
Worksheet worksheet = workbook.Worksheets[0]; | |
int moduleIndex = workbook.VbaProject.Modules.Add(worksheet); | |
// Access the VBA Module | |
VbaModule module = workbook.VbaProject.Modules[moduleIndex]; | |
// Set module name | |
module.Name = "TestModule"; | |
// Set module code | |
module.Codes = | |
@"Private Sub Worksheet_Change(ByVal Target As Range) | |
' Check if the changed cell is A1 | |
If Target.Address = ""$A$1"" Then | |
' Check if the changed cell is not empty | |
If Target.Value <> """" Then | |
' Display a message box | |
MsgBox ""Text entered in cell A1: "" & Target.Value, vbInformation, ""Cell A1 Change"" | |
End If | |
End If | |
End Sub | |
"; | |
// Save the workbook | |
workbook.Save("output.xlsm", SaveFormat.Xlsm); | |
Console.WriteLine("VBA code added successfully"); | |
} | |
} |
此示例代码演示了如何在 Excel 文件中使用 C#* 访问 VBA 代码库并添加模块和代码。每当单元格 A1 值更改时,模块中的示例代码都会在 MS Excel 中显示一个消息框。此消息框包含单元格中的更新值,但是,您可以根据您的要求更改代码。
本文教我们向 Excel 文件添加宏。要在 Excel 中显示公式,请参阅有关 如何使用 C# 在 Excel 中显示公式 的文章。