xlwings:如何将现有UDF导入至其他工作簿?
Ah, I see the issue here—you're mixing up what the "UDF Modules" field in the xlwings ribbon expects! Let's break this down and fix it step by step:
Why the Error Happens
The ModuleNotFoundError pops up because you're entering the full file path (C:\Test\myproject\myproject.py) into the UDF Modules field, but xlwings doesn't work that way. It expects a module name (not a path), and it needs the folder containing your script to be in Python's search path so it can locate the module.
Step-by-Step Fix
Identify your module's root folder
Your scriptmyproject.pylives inC:\Test\myproject—this folder is the one we need Python to recognize as a valid location for modules.Add the folder to Python's search path
You have two options here:- Temporary (per-workbook) fix:
Open the xlwings ribbon in your target workbook, click "Settings", then look for the "Extra Paths" section. AddC:\Test\myprojecthere and save the settings. - Permanent (system-wide) fix:
AddC:\Test\myprojectto your system'sPYTHONPATHenvironment variable. This way, any Python environment (including xlwings) will be able to find your module without extra per-workbook setup.
- Temporary (per-workbook) fix:
Update the UDF Modules field
Go back to the "UDF Modules" field in the xlwings ribbon, and replace the full path with justmyproject(that's your script name without the.pyextension).Import the UDFs
Click the "Import UDFs" button in the xlwings ribbon—your functions should now load without errors!
Extra Checks
- Make sure
myproject.pyhas no syntax errors—even a tiny typo can block UDF loading. - If you're using a virtual environment, double-check that xlwings is configured to use the correct Python interpreter (you can set this in the xlwings Settings under "Python Interpreter").
内容的提问来源于stack exchange,提问作者calvinXS

