获取调用脚本的工作簿的位置

Get location of the workbook calling the script

我正在尝试使用

从Excel执行以下Python脚本
Sub MacrosTrigger()
    RunPython ("import MacrosTrigger")
End Sub

MacrosTrigger.py包含以下示例代码

import os
import pandas as pd
import glob
import matplotlib.pyplot as plt
import matplotlib
import xlwings as xw
matplotlib.rcParams['figure.figsize'] = (18.0, 5.0)
wb = xw.Book.caller()
cwd = os.getcwd()
wb.sheets[0].range('A1').value = cwd
os.chdir('C:\Users\HegdeP\Desktop\Python Data Analysis\PST')

os.getcwd() returns Python 解释器的位置。出于自动化目的,我希望能够 return 调用脚本的工作簿的位置。即 wb 的位置。

xlwings.Book 的绝对路径可以通过 fullname 属性获得,所以在你的情况下 wb.fullname.

您在评论中说您仅指的是文件夹名称。在这种情况下,使用

foldername = os.path.dirname(wb.fullname)

查看 os.path 的文档,了解许多其他处理文件名的有用函数。