Hantera Excel makrobokkoderna.

Lägg till en VBA-modul i C#

Följande provkod skapar en ny arbetsbok och lägger till en ny VBA-modul och makrokod och sparar utdata i XLSM-format. När du öppnar utdata-XLSM-filen i Microsoft Excel och klickar på Utvecklare > Visuell grund-menykommandon kommer du att se en modul som heter “TestModule” och inuti den kommer du att se följande makrokod.

 Sub ShowMessage()

    MsgBox "Welcome to Aspose!"

End Sub

Här är provkoden för att generera utdata i XLSM-format med VBA-modul och makrokod.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create new workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Add VBA Module
int idx = workbook.VbaProject.Modules.Add(worksheet);
// Access the VBA Module, set its name and codes
Aspose.Cells.Vba.VbaModule module = workbook.VbaProject.Modules[idx];
module.Name = "TestModule";
module.Codes = "Sub ShowMessage()" + "\r\n" +
" MsgBox \"Welcome to Aspose!\"" + "\r\n" +
"End Sub";
// Save the workbook
workbook.Save(dataDir + "output_out.xlsm", SaveFormat.Xlsm);

Modifiera VBA eller makro i C#

Följande provkod laddar käll-Excel-filen som har följande VBA- eller makrokod inuti den

 Sub Button1_Click()

    MsgBox "This is test message."

End Sub

Efter att Aspose.Cells provkoden har körts kommer VBA- eller makrokoden att modifieras på detta sätt

 Sub Button1_Click()

    MsgBox "This is Aspose.Cells message."

End Sub

Du kan ladda ner den källa Excel-filen och den utdata Excel-filen från de angivna länkarna.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create workbook object from source Excel file
Workbook workbook = new Workbook(dataDir + "sample.xlsm");
// Change the VBA Module Code
foreach (VbaModule module in workbook.VbaProject.Modules)
{
string code = module.Codes;
// Replace the original message with the modified message
if (code.Contains("This is test message."))
{
code = code.Replace("This is test message.", "This is Aspose.Cells message.");
module.Codes = code;
}
}
// Save the output Excel file
workbook.Save(dataDir + "output_out.xlsm");

Fortsatta ämnen