Home > Software design >  Excel delete column with win32com
Excel delete column with win32com

Time:10-03

I could not find one adequate documentation for the win32com library Can you please tell me how to delete a column in Excel using this library? I guess it looks something like this:

excel = win32com.client.Dispatch("Excel.Application")
wb = excel.Workbooks.Open(path_on_file)
ws = wb.Worksheet("Sheet1")
ws.DeleteColumn(1, 3)

But how exactly can this be done?

CodePudding user response:

You are accessing the same COM objects that VBA would access, so you can simply refer to the VBA docs.

There you will find that you can get the column or range that you want and then delete it as follows:

for i in range(3, 0, -1):
  ws.Columns(i).Delete()

# or

ws.Range("A:C").Delete()

Note that for the individual deletions, I'm deleting them backwards, otherwise the indices would shift during deletion.

Also, you have a typo in your code, it should be .Worksheets("Sheet1") with "worksheets" as plural.

  • Related