Excel win32com programming with Python. Passing Parameters to function

江枫思渺然 提交于 2019-12-09 21:28:26

问题


I suspect there is an easy answer for this question but I can't find it anywhere! I am writing a function to plot a lot of data in excel and I am controlling the plotting with Python. I have generated all of the charts and each chart is its own sheet, but they are out of order. The VBA code for this is:

Sheets("Chart1").Move After:=Sheets(3)

This will take "Chart1" and move it after the 3rd sheet. How do I do this in Python? I know that the code is something along the lines of:

xlChart.Move(Before,After)

How do I tell python the Before and After parameters? I guess the big thing is I haven't figured out how to pass parameters in win32com programming.

Thanks in advance for any help!


回答1:


Here's a very simple example:

from win32com import client

excel=client.Dispatch("Excel.Application")
excel.Visible=True
book=excel.Workbooks.Open("c:/desktop/test.xlsx", False, True)
sheet=book.Worksheets(1)
chart=book.Charts.Add()
chart.SetSourceData(sheet.Range("$A:$B"))

chart.Move(Before=book.Worksheets("Sheet2"))
chart.Move(book.Worksheets("Sheet2"))#equivalent to previous line
chart.Move(book.Worksheets("Sheet2"), None)#also equivalent

chart.Move(After=book.Worksheets("Sheet2"))
chart.Move(None,book.Worksheets("Sheet2"))#equivalent to previous line

I've tried to show the various options for dealing with optional parameters which are important issues with Excel COM programming. You can use positional parameter passing and omit parameters from the end. Or you can pass None which is equivalent. Finally, you can used named parameters.



来源:https://stackoverflow.com/questions/5305297/excel-win32com-programming-with-python-passing-parameters-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!