Gestisci i codici VBA della cartella di lavoro con attivazione macro di Excel.

Aggiungi un modulo VBA in C#

Il seguente codice di esempio crea una nuova cartella di lavoro e aggiunge un nuovo modulo VBA e codice macro e salva l’output nel formato XLSM. Una volta, aprirai il file di output XLSM in Microsoft Excel e fai clic sulSviluppatore > Visual Basic comandi di menu, vedrai un modulo chiamato “TestModule” e al suo interno vedrai il seguente codice macro.

 Sub ShowMessage()

    MsgBox "Welcome to Aspose!"

End Sub

Ecco il codice di esempio per generare il file di output XLSM con il modulo VBA e il 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 VBA o Macro in C#

Il seguente codice di esempio carica il file Excel di origine che contiene un codice VBA o macro seguente

 Sub Button1_Click()

    MsgBox "This is test message."

End Sub

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

 Sub Button1_Click()

    MsgBox "This is Aspose.Cells message."

End Sub

Puoi scaricare ilfile Excel di origine e ilfile Excel di output dai link indicati.

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