3

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That is a perfect explanation! Thank you so much! I finally understand how to handle optional parameters.
Range.BorderAround call will fail if you try to pass None to int arguments. pythoncom.Empty should be passed to omit argument as i understand.
And what about if i need to copy some data, from sheet1 workbook1, to sheet2 workbook2. I know how to do it before the sheet2 or after the sheet2, but what about in the sheet2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.