0

I found this code online. It's used to extract a sheet from every excel wb in a directory. I'm still learning Python so I don't know what I should be asking exactly.

The error says "sheets" is not defined. Fair enough, but this is the code I found and it says it works. I don't really know what to define here.

import os
import win32com.client
 
path = "C:/Folder"  #This folder contains the spreadsheets
pathmaster = "C:/Desktop/MyFile.xlsx"
 
xl = win32com.client.DispatchEx('Excel.Application')
xl.Visible = False
 
wbmaster = xl.Workbooks.Open(Filename=pathmaster)
 
os.listdir(path)
 
for sheet in sheets:
    print(sheet)
    wb1 = xl.Workbooks.Open(Filename=os.path.join(path, sheet))
 
    ws1 = wb1.Worksheets(4)
    ws1.Name = sheet[:4]
 
    ws1.Copy(Before=wbmaster.Worksheets(1))
    wb1.Close(True)
 
wbmaster.Close(SaveChanges=True)
Mofongo
  • 131
  • 8

2 Answers2

0

As you said 'sheets' is undefined. To fix this you need to declare it above your call to it for sheet in sheets: Here is how you can fix it.

Change your code to...

wbmaster = xl.Workbooks.Open(Filename=pathmaster)
for sheet in wbmaster.Sheets:
    # Do code here

Check out these other past answers

  1. How can I iterate over worksheets in win32com?
  2. Python: Open Excel Workbook using Win32 COM Api
John Salzman
  • 500
  • 5
  • 14
0

You must define what is sheets before use in the for loop maybe you must use : for sheet in wbmaster