Skip to content

Instantly share code, notes, and snippets.

@israel-dryer
Created September 7, 2020 15:10
Show Gist options
  • Save israel-dryer/bc92cd8bd960492f2cbce617db68cf5e to your computer and use it in GitHub Desktop.
Save israel-dryer/bc92cd8bd960492f2cbce617db68cf5e to your computer and use it in GitHub Desktop.
Find Excel table range with win32com

Find Excel Range in Workbook

import win32com.client as client
import pathlib

Initialize the application

excel = client.Dispatch('Excel.Application')

Open the file

filepath = r'C:\Users\admin\Documents\personal_income.xlsx'
wb = excel.Workbooks.Open(filepath)

Select the appropiate sheet

sheet = wb.Worksheets[0]

# display the excel program (optional)
excel.Visible=True

Commonly used directional enumerations

xlDown = -4121
xlToLeft = -4159
xlToRight = -4161
xlUp = -4162
xlLastCell = 11

Method 1

last_cell = sheet.Range('A1').End(xlDown).End(xlToRight)
table_range = sheet.Range('A1', last_cell)

Method 2

last_cell = sheet.Cells(1, 1).SpecialCells(xlLastCell)
table_range = sheet.Range('A1', last_cell)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment