在python代码中嵌入VB宏
我对win32com模块的使用是新手。我在web上找到以下生成excel的代码:在python代码中嵌入VB宏,python,python-2.7,python-3.x,pywin32,win32com,Python,Python 2.7,Python 3.x,Pywin32,Win32com,我对win32com模块的使用是新手。我在web上找到以下生成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()
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()
如果答案解决了你的问题,你能标记一下吗?