在 python 代码中嵌入 VB 宏

Embedding VB macro in python code

我是 win32com 模块的新手。以下是我在网上找到的用于生成 excel 的代码:

import win32com.client as win32
class generate_excel:
    def excel(self):
        excel = win32.gencache.EnsureDispatch('Excel.Application')
        excel.Visible = True
        wb = excel.Workbooks.Add()
        ws = wb.Worksheets('Sheet1')
        ws.Name = 'Share'
        ws.Range(ws.Cells(2,2),ws.Cells(2,3)).Value = [1,70]
        ws.Range(ws.Cells(3,2),ws.Cells(3,3)).Value = [2,90]
        ws.Range(ws.Cells(4,2),ws.Cells(4,3)).Value = [3,92]
        ws.Range(ws.Cells(5,2),ws.Cells(5,3)).Value = [4,95]
        ws.Range(ws.Cells(6,2),ws.Cells(6,3)).Value = [5,98]
        wb.SaveAs('hi.xlsx')
        excel.Application.Quit()            
d=generate_excel()
d.excel()

在这段代码中,我想添加一个 VB 脚本来在 excel 关闭之前绘制饼图。 VB脚本如下:

Sub Macro2()
'
' Macro2 Macro
'

'
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlPie
    ActiveChart.SetSourceData Source:=Range("C2:C6")
End Sub

请告诉我如何将其嵌入到我的 Python 脚本中。

有点晚了,您可能已经找到了解决方案,但希望这对其他人有所帮助。

from win32com.client import DispatchEx

# Store vba code in string
vbaCode = """
Sub Macro2()
'
' Macro2 Macro
'

'
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlPie
    ActiveChart.SetSourceData Source:=Range("C2:C6")
End Sub
"""

# Init Excel and open workbook
xl = DispatchEx("Excel.Application")
wb = xl.Workbooks.Add(path_to_workbook)

# Create a new Module and insert the macro code
mod = wb.VBProject.VBComponents.Add(1)
mod.CodeModule.AddFromString(vbaCode)

# Run the new Macro
xl.Run("Macro2")

# Save the workbook and close Excel
wb.SaveAs(path_to_file, FileFormat=52)
xl.Quit()