在 Java 中的 Excel VBA 库中添加模块

本文指导如何在 Java 中的 Excel VBA 库中添加模块。它包含设置开发环境的详细信息、编程任务列表以及演示在 Java 中的 VBA 代码库 中添加模块的示例代码。您还将学习如何设置各种模块属性,例如展示 Excel 文件宏开发的 VBA 代码。

用Java修改Excel VBA代码库的步骤

  1. 将 IDE 设置为使用 Aspose.Cells for Java 来处理 VBA
  2. 实例化一个 Workbook 对象,访问一个 sheet,并为所选工作表添加一个模块
  3. 从工作簿访问新模块并设置其名称
  4. 编写并测试VBA代码并将其用作模块中的codes属性
  5. 如果需要,将输出 Excel 文件以 XLSM 形式保存在磁盘或流上

这些步骤总结了在 Java* 中添加 *Excel VBA 源代码库的过程。该过程很简单,因为它需要工作簿中的工作表来添加新的 VbaModule,然后在其中设置一些属性。使用多行 VBA 代码设置属性代码以使宏可运行。

用Java在Excel宏库中添加代码的代码

import com.aspose.cells.*;
public class Main
{
public static void main(String[] args) throws Exception // Add VBA Code in Java
{
// Set the licenses
new License().setLicense("License.lic");
// Create a workbook
Workbook wb = new Workbook();
// Select a sheet
Worksheet ws = wb.getWorksheets().get(0);
// Add VBA Module and get its reference
int idx = wb.getVbaProject().getModules().add(ws);
VbaModule module = wb.getVbaProject().getModules().get(idx);
// Assign a name to the module
module.setName("SetGreenEven");
// Set code for the module
module.setCodes("""
Private Sub Worksheet_Change(ByVal Target As Range)
' Verify if updated cell is within a specified range
If Not Intersect(Target, Range("A1:Z100")) Is Nothing Then
' Loop through all cells
For Each Cell In Target
' Check the cell value and apply formatting accordingly
If Cell.Value >= 80 Then
Cell.Interior.Color = RGB(0, 255, 0) ' Green
ElseIf Cell.Value >= 50 And Cell.Value < 80 Then
Cell.Interior.Color = RGB(255, 165, 0) ' Orange
ElseIf Cell.Value < 50 Then
Cell.Interior.Color = RGB(152, 133, 88) ' Dark Tan
Else
' Reset the background color if none of the conditions are met
Cell.Interior.ColorIndex = xlNone
End If
Next Cell
End If
End Sub
""");
// Save the output
wb.save("sampleWithMacro.xlsm", SaveFormat.XLSM);
System.out.println("Done");
}
}

此代码片段展示了如何访问 Java 中的 VBA 代码库并添加其中包含代码的模块。在此示例代码中,我们设置了根据 VBA 代码中定义的值范围更改单元格颜色的名称和代码。您可以使用另一个重载方法添加模块,该方法将 VbaModuleType 枚举器值作为参数,其中包括 CLASS、DESIGNER、DOCUMENT 和 PROCEDURAL。

本文教我们在 Excel 文件中创建新的宏。要在 Excel 中应用条件格式,请参阅有关 使用 Java 在 Excel 中应用条件格式 的文章。

 简体中文