在python代码中嵌入VBA宏

时间:2015-02-14 10:00:02

标签: python python-2.7 python-3.x pywin32 win32com

我是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()

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

Sub Macro2()
'
' Macro2 Macro
'

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

请告诉我如何在Python脚本中嵌入它。

1 个答案:

答案 0 :(得分:2)

有点迟了,你可能已经找到了一个解决方案,但希望这有助于其他人。

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