python - 在Python代码中嵌入VB宏

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

在这段代码中,我想添加一个 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()

关于python - 在Python代码中嵌入VB宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28514425/

相关文章:

python-2.7 - Python(2.7)使用套接字和选择模块进行多重聊天(非阻塞代码)

python - 为什么该服务器程序无法向客户端发送任何内容?

python-3.x - Python 在生成器中查找类型和返回类型

python-3.x - 以 id 作为键,将多个标签读取为列表或字典中的元组,即 {id :(cat1, cat2,.....)}

python - Django 多表继承与单独的(相同的)表没有指针

python - 使用 mysql 创建图表

django - 使用 Django 配置 mongoDB

python - 添加 [别名] 失败,错误为 : invalid command 'xyz'

python - 如何获取 anchor 标签内的元素?

python - pydub AudioSegment.export 正在锁定 smb 共享上的文件。无法删除该文件