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

Aggiungi un modulo VBA in Python

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.

from aspose.cells import SaveFormat, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# The path to the documents directory.
dataDir = RunExamples.GetDataDir(".")
# Create new workbook
workbook = Workbook()
# Access first worksheet
worksheet = workbook.worksheets[0]
# Add VBA Module
idx = workbook.vba_project.modules.add(worksheet)
# Access the VBA Module, set its name and codes
module = workbook.vba_project.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 Python

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 for Python via .NET, il codice VBA o Macro verrà modificato così

 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.

from aspose.cells import Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# The path to the documents directory.
dataDir = RunExamples.GetDataDir(".")
# Create workbook object from source Excel file
workbook = Workbook(dataDir + "sample.xlsm")
# Change the VBA Module Code
for module in workbook.vba_project.modules:
code = module.codes
# Replace the original message with the modified 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