import win32com.client
#Attach to the running excel
excel = win32com.client.GetActiveObject("Excel.Application")
workbook = excel.ActiveWorkbook
worksheet = workbook.ActiveSheet
active_cell = excel.ActiveCell
#Copy the active cell
active_cell.Copy()
I am writing a python script to copy the active cell from an open excel workbook and auto search it online. I have opened the workbook but still got an AttributeError: 'NoneType' object has no attribute 'ActiveSheet'. Any advice is welcome. Thanks in advance.
GetActiveObject is used to connect to any already running Excel instance
If you want to open or create a workbook then
This code will create two workbook objects
Existing Excel file and new created workbook.
import win32com.client
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
# excel.Visible = True # Workbook visible or not
### Open an existing Excel file
workbook1 = excel.Workbooks.Open('C:\Temp\foo.xlsx')
worksheet1 = workbook1.Worksheets('Sheet1') # or activesheet can be used
### Create a new workbook with default Sheet
workbook2 = excel.Workbooks.Add()
worksheet2 = workbook2.ActiveSheet
Also the following Post on using Dispatch and encache.EnsureDispatch may be useful