Etkinleştirilmiş Çalışma Kitabının VBA Kodlarını Yönet

Python’da VBA Modülü Ekle

Aşağıdaki örnek kod yeni bir çalışma kitabı oluşturur ve yeni bir VBA Modülü ve Makro Kodu ekler ve çıktıyı XLSM biçiminde kaydeder. Bir kez çıktı XLSM dosyasını Microsoft Excel’de açarsanız ve Geliştirici > Görsel Temel menü komutlarına tıklayarak “TestModülü” adlı bir modül göreceksiniz ve içinde aşağıdaki makro kodunu göreceksiniz.

 Sub ShowMessage()

    MsgBox "Welcome to Aspose!"

End Sub

Aşağıdaki örnek kod, VBA Modülü ve Makro Kodu içeren kaynak Excel dosyasını yükler

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)

Python’da VBA veya Makro Değiştir

Aşağıdaki örnek kod, içinde belirtilen VBA veya Makro kodu bulunan kaynak Excel dosyasını yükler

 Sub Button1_Click()

    MsgBox "This is test message."

End Sub

Aspose.Cells for Python via .NET örnek kodunun yürütülmesinden sonra, VBA veya Makro kodu şu şekilde değiştirilecektir

 Sub Button1_Click()

    MsgBox "This is Aspose.Cells message."

End Sub

Verilen bağlantılardan kaynak Excel dosyasını ve çıktı Excel dosyasını indirebilirsiniz.

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

Gelişmiş Konular