Reputation: 2207
I'm not able to open or call the current active workbook using xlwings. I'm on macOS Sonoma 14.5 and xlwings v0.31.10.
I keep getting this error (I'm running the .py file out of 4. Master):
UnboundLocalError: cannot access local variable 'mount_point' where it is not associated with a value
My Excel file is on a SharePoint which is synced to my OneDrive folder locally.
I've also configured ONEDRIVE_CONSUMER_MAC
(to /Users/John/OneDrive - MyCompany) and ONEDRIVE_COMMERCIAL_MAC
(to /Users/John/OneDrive - MyCompany 2) in my environment variables in ~/.bash_profile
I've tried something very simple but can't get it to work.
import xlwings as xw
def getWB():
try:
wb =xw.Book.caller() #never works
except:
wb = xw.Book("/Users/John/Library/CloudStorage/OneDrive-MyCompany/Project XYZ/2. Excel/4. Master/Name of Excel file.xlsm").set_mock_caller()
wb =xw.Book.caller()
return wb
def main():
wb = getWB()
sheet = wb.sheets[0]
if sheet["E4"].value == "Hello xlwings!":
sheet["E4"].value = "Bye xlwings!"
else:
sheet["E4"].value = "Hello xlwings!"
if __name__ == "__main__":
app = xw.App()
main()
I'd appreciate any help! Thank you!
Upvotes: 0
Views: 107
Reputation: 6620
Are you trying to connect to an already running instance of Excel?
If a workbook called 'foo.xlsx' is already open and you want to access it then...
import xlwings as xw
"""
def getWB():
try:
wb =xw.Book.caller() #never works
except:
wb = xw.Book("/Users/John/Library/CloudStorage/OneDrive-MyCompany/Project XYZ/2. Excel/4. Master/Name of Excel file.xlsm").set_mock_caller()
wb =xw.Book.caller()
return wb
"""
def main():
### Connect to the already open Excel workbook called 'foo.xlsx' or open if its not.
wb = xw.Book('foo.xlsx')
sheet = wb.sheets[0]
if sheet["E4"].value == "Hello xlwings!":
sheet["E4"].value = "Bye xlwings!"
else:
sheet["E4"].value = "Hello xlwings!"
### Waiting to end
input("Waiting!")
if __name__ == "__main__":
app = xw.App(visible=False)
main()
It is usually better to use in a context manager for clean up
though this will close the workbook as well at the end if it wasn't already open.
import xlwings as xw
with xw.App(visible=False) as xl:
### Connect to the already open Excel workbook called 'foo.xlsx' or open if its not.
wb = xw.Book('foo.xlsx')
sheet = wb.sheets[0]
if sheet["E4"].value == "Hello xlwings!":
sheet["E4"].value = "Bye xlwings!"
else:
sheet["E4"].value = "Hello xlwings!"
input("Waiting!")
Disclaimer
This is true for windows but expect that MACOS would act the same.
Upvotes: 2