簡體   English   中英

從 python 執行 LibreOffice Calc Basic 宏

[英]Execute LibreOffice Calc Basic macro from python

我正在嘗試使用 Python 自動化 LibreOffice 電子表格。 我得到一個桌面並打開電子表格

file_url = uno.systemPathToFileUrl(os.path.abspath("/path/to/file/estimation.xlsm"))
doc = desktop.loadComponentFromURL(file_url, "_blank", 0, oo_properties(MacroExecutionMode=4))

以下代碼將打印基本腳本

the_basic_libs = doc.BasicLibraries
the_vba = the_basic_libs.getByName("VBAProject")
the_takerate = the_vba.getByName("TakeRate")
print(the_takerate)

打印的模塊的第一行是:

Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1

Public Sub TakeRateScenarioAnalysis()
Dim StartCell As Range

我得到了腳本

oor = OORunner()
msp = oor.get_context().getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
sp = msp.createScriptProvider("")
scriptx = sp.getScript("vnd.sun.star.script:VBAProject.TakeRate.TakeRateScenarioAnalysis?language=Basic&location=document")

返回以下錯誤

Traceback (most recent call last):
  File "./runProjectEstimate.py", line 198, in <module>
    scriptx = sp.getScript("vnd.sun.star.script:VBAProject.TakeRate.TakeRateScenarioAnalysis?language=Basic&location=document")
__main__.ScriptFrameworkErrorException: The following Basic script could not be found:
library: 'VBAProject'
module: 'TakeRate'
method: 'TakeRateScenarioAnalysis'
location: 'document'

腳本 URI 有問題嗎? 我不知道為什么我可以打印腳本但腳本提供者找不到它。

以下對我有用:

scriptx = sp.getScript(
    'vnd.sun.star.script:Standard.Module1.TakeRateScenarioAnalysis?'
    'language=Basic&location=application')

但是,正如您的問題中所述,這沒有:

scriptx = sp.getScript(
    "vnd.sun.star.script:VBAProject.TakeRate.TakeRateScenarioAnalysis?"
    "language=Basic&location=document")

從這些結果來看,當宏存儲在文檔中時,似乎不可能以這種方式調用宏。 這很可能是權限問題。 從可能由其他人創建的文檔中調用宏是傳播病毒的好方法,因此 LO 試圖阻止這種情況。

將您的VBAProject庫移動到My Macros而不是文檔中是否可以接受? 然后一切都應該按預期工作。

一些相關鏈接可能會提供更多想法:

編輯

有一種方法可以調用存儲在文檔中的宏。 從文檔中獲取腳本提供者,而不是主腳本提供者。

oScriptProvider = doc.getScriptProvider()
oScript = oScriptProvider.getScript(
    "vnd.sun.star.script:Standard.Module1.SayHello?"
    "language=Basic&location=document")
oScript.invoke((), (), ())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM