Forum Discussion
Python in Excel iteration of sheets
- Jan 18, 2024
Python in Excel doesn't work with such kind of indirect references, i.e.
a = "Sheet2!A1:A2" xl(a)
returns the same error. xl() accepts direct names of the Excel objects.
- ChrisCarpenterJan 18, 2024Copper Contributor
Thank you for a response.
I would agree with you if it weren't for the fact that it works after another direct loading of those specific cells line pointing to the sheet.
for i in range(2,4): value = f"Sheet{i}!A1:A2" print(xl(value))
Does not work for Sheet2, however,
xl("Sheet2!A1:A2") for i in range(2,4): value = f"Sheet{i}!A1:A2" print(xl(value))
For Sheet2 does work
xl("Sheet2!A1:A3") for i in range(2,4): value = f"Sheet{i}!A1:A2" print(xl(value))
Does not work for Sheet2
Very strange.
- EricAshtonJan 14, 2025Copper Contributor
Yes I am having the same problem - getting a "key error" when trying to use xl() with a variable. I would love it if someone had a way to make this work. Or if it could be added in a future update. I have also noticed that it sort of works if you hardcode the cells elsewhere the load them using xl() which is very strange but not super helpful.
- SergeiBaklanJan 18, 2024Diamond Contributor
Python in Excel doesn't work with such kind of indirect references, i.e.
a = "Sheet2!A1:A2" xl(a)
returns the same error. xl() accepts direct names of the Excel objects.
- ChrisCarpenterJan 18, 2024Copper ContributorSo by extension there is no way to reference all of a particular range across all sheets?
That's a shame. I was trying to convert my py scripts with openpyxl into excel itself.
- peiyezhuJan 18, 2024Bronze Contributorxl("Sheet2!A1:A2")
I guess you are using Excel Python formular rather than run .py script in local python environment.
xl(..) does not belong to python native methods.
So,maybe this result in the strange behaviour.- ChrisCarpenterJan 18, 2024Copper ContributorYeah I was trying to convert my openpyxl scripts to work within excel so I could have users paste the code and it work without teaching them how to install python or manually adjust code to run it.
As Sergei posted I guess Python in Excel doesn't accept indirect references which is quite unfortunate.