Python win32com显示VBA用户窗体 [英] Python win32com Show VBA UserForm
问题描述
我正在尝试使用win32com使用Python3脚本控制Word 2016。我已经导入了一个VBA用户窗体,我试图显示它但收到错误。一些Python代码:
I'm trying to control Word 2016 using a Python3 script using win32com. I've imported a VBA UserForm, and am trying to show it but receiving an error. Some Python code:
from win32com.client.dynamic import Dispatch
from win32com.client.dynamic import ERRORS_BAD_CONTEXT
import win32com.client as win32
app = win32.gencache.EnsureDispatch('Word.Application')
app.Visible = True
app.Documents.Open('.../'+current_doc+'.docx')
try:
app.VBE.VBProjects(1).VBComponents.Import('.../UserForm1.frm')
app.Run('UserForm_Initialize()')
该脚本成功导入UserForm,但在尝试初始化时,它会抛出此错误:
The script succesfully imports the UserForm, but upon attempting to initialize, it is throwing this error:
com_error: (-2147352567, 'Exception occurred.', (0, 'Forms.Form.1', "Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.", 'fm20.hlp', 0, -2147352573), None)
有没有人知道成功初始化UserForm的方法?为什么不让我以这种方式初始化UserForm?
谢谢!!!
注意:我已经通过单独导入模块来调用UserForm并运行它来验证app.Run()命令是否正确。同样的错误。但是,如果我然后打开VBA控制台并运行相同的模块,它会成功打开UserForm。
Does anyone know a way to initialize the UserForm successfully? Why won't it let me initialize the UserForm in this way?
Thanks!!!
Note: I've verified the app.Run() command is correct by also separately importing a module to call the UserForm, and running it. Same error. However, if I then open the VBA console and run the same module, it successfully opens the UserForm.
推荐答案
嗨SpennyEco,
Hi SpennyEco,
根据我的搜索,我认为您得到的错误是因为您要从Word调用的文档与您在python代码中引用的名称不匹配,或者它可能是路径错误。
According to my search, I assume that the error that you get is because the document you wanted to call from Word did not match the name you was referencing in your python code or it maybe a path error.
首先,您可以使用以下代码获取有关该错误的更多信息:
First, you can use the code below to get more information about that error:
import win32api
e_msg = win32api.FormatMessage(-2147352565)
print e_msg.decode('CP1251')
如需了解更多信息,请查看以下链接:
For more information, please review the following links:
pywintypes.com_error用Python打开Excel
希望它可以帮到你。
最诚挚的问候,
Yuki
这篇关于Python win32com显示VBA用户窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!