Gestire i codici VBA della cartella di lavoro abilitata per i macro di Excel.

Aggiungi un modulo VBA in C#

Il seguente codice di esempio crea un nuovo workbook e aggiunge un nuovo modulo VBA e codice macro e salva l’output nel formato XLSM. Una volta aperto il file XLSM di output in Microsoft Excel e fare clic sui comandi del menu Sviluppo > Visual Basic, verrà visualizzato un modulo chiamato “TestModule” e al suo interno verrà visualizzato il seguente codice macro.

 Sub ShowMessage()

    MsgBox "Welcome to Aspose!"

End Sub

Qui si trova il codice di esempio per generare il file XLSM di output con un modulo VBA e un codice macro.

// 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);

Modifica il VBA o il macro in C#

Il seguente codice di esempio carica il file Excel di origine che contiene il seguente codice VBA o Macro al suo interno

 Sub Button1_Click()

    MsgBox "This is test message."

End Sub

Dopo l’esecuzione del codice di esempio di Aspose.Cells, il codice VBA o Macro sarà modificato in questo modo

 Sub Button1_Click()

    MsgBox "This is Aspose.Cells message."

End Sub

Puoi scaricare il file Excel di origine e il file Excel di output dai link forniti.

// 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");

Argomenti avanzati