Adding Worksheets to an Excel Workbook

John Machin sjmachin at lexicon.net
Tue Oct 10 23:59:12 CEST 2006


e.h.doxtator at accenture.com wrote:
> All
>
> I'm a Python newbie, and I'm just getting to the wonders of COM
> programming.  I am trying to programmatically do the following:
>
> 1.  Activate Excel
> 2.  Add a Workbook
> 3.  Add a Worksheet
> 4.  Populate the new Worksheet
> 5.  Repeat steps 3,4 while there is data.
>
> How do you add a Worksheet to a Workbook?

To find out how to do things, you can:

(1) use the VBA help in Excel.

You would find (eventually):
"""
Add method as it applies to the Sheets and Worksheets objects.

Creates a new worksheet, chart, or macro sheet. The new worksheet
becomes the active sheet.

expression.Add(Before, After, Count, Type)
expression    Required. An expression that returns one of the above
objects.

Before   Optional Variant. An object that specifies the sheet before
which the new sheet is added.

After   Optional Variant. An object that specifies the sheet after
which the new sheet is added.

Count   Optional Variant. The number of sheets to be added. The default
value is one.

Type   Optional Variant. Specifies the sheet type. Can be one of the
following XlSheetType constants: xlWorksheet, xlChart,
xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a
sheet based on an existing template, specify the path to the template.
The default value is xlWorksheet.

Remarks
If Before and After are both omitted, the new sheet is inserted before
the active sheet.
"""
so,
    your_handle.Worksheets.Add()
looks like what you need.

(2) Again in Excel, use the "record a macro" facility: turn on
recording, do your thing, stop recording, inspect the generated macro.

In this case, this gave
    Sheets.Add
which you translate to
    your_handle.Sheets.Add()

What's the difference between Sheets and Worksheets? I dunno. Try both.
Look in the Excel VBA help.

HTH,
John




More information about the Python-list mailing list