I'm trying to perform two actions: 1) Check to see if a worksheet exists in a workbook using xlwings 2) Use a variable name to activate the worksheet using xlwings.
The worksheet name is a variable, so I can't use the sheets[0] option or sheets['name'] option.
import xlwings as xw
app = xw.apps.active
wb = app.books.active
key1 = 'BUS'
if key1 in wb:
sht = wb.sheets.activate(key1)
else:
sht = wb.sheets.add(key1)
I get the error: AttributeError: 'Sheets' object has no attribute 'activate'
You should slightly rewrite your code to get this working. Tested this by opening a new Excel workbook and running the code a few times.
# python 3.7.3
# xlwings 0.15.8
import xlwings as xw
app = xw.apps.active
wb = app.books.active
key1 = 'BUS'
if key1 in [sh.name for sh in wb.sheets]:
sht = wb.sheets[key1]
else:
sht = wb.sheets.add(key1)
Changes:
xlwings. As soon as you assign the sheet you want to work in to your sht variable, all actions will be performed on this sheet. You can also create a separate variable for every sheet (e.g. sht_bus, sht_train, ...)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With