我有一个从 MS Word 2003 模板 (.dot) 中的 VBA AutoNew() 子函数调用的 python 脚本 - 因此每次从此 Word 模板创建文档时它都会运行。
第三方应用程序从此模板创建文档。第三方应用程序如何设置文档存在许多格式问题,因此我的脚本会在第三方脚本完成运行后对其进行调整。 (我最初是用 VBA 编写脚本的,但是 VBA 计时器的问题导致它在很大一部分时间里崩溃。Python 版本工作得完美无缺。)
我希望脚本只处理调用它的文档,该文档始终是最近打开的 Word 文件。 (该文件是 .doc 而不是 .docx,如果这有什么区别的话。)我找到了三种获取打开的 Word 实例的方法(因为该脚本是由 AutoNew 调用的,所以将始终有一个可用的打开实例):
win32com.client.GetActiveObject (Class = 'Word.Application')
win32com.client.gencache.EnsureDispatch('Word.Application')
win32com.client.Dispatch('Word.Application')
如果新创建的文档是唯一打开的 Word 文件,那么这三个文件中的任何一个都可以很好地工作。但是,如果 Word 文档已打开,并且我运行第三方软件从该模板创建新文档,则 python 脚本每次都会使用所有三种方法获取旧实例。
我尝试寻找循环遍历Word文档的方法,想法是我可以检查所有名称并选择最后数字最大的那个(在脚本运行时,文档不会被保存,所以它的名称将是 Document1、Document2 等)不幸的是,我只找到了循环关闭文档的方法(打开一个、做某事、关闭它、继续下一个),而不是(如我的情况)已经打开的文档。
有没有办法将 python 定向到最近打开的 Word 文档?
EDIT相关问题:Word VBA 和多个 Word 实例
我找到了如何获取我想要控制的文档的 Windows 句柄整数:
import win32gui
import re
#Create a list of all open Microsoft Word document titles and their
#handle integers
titles = []
def foreach_window(hwnd, lParam):
if win32gui.IsWindowVisible(hwnd):
title = win32gui.GetWindowText(hwnd)
if 'Microsoft Word' in title:
titles.append([title, hwnd])
return True
win32gui.EnumWindows(foreach_window, None)
#Find the handle of the newest open, unsaved Word document
winOrder = []
for s in titles:
item = re.search(r'Document\d', s[0])
if item:
winOrder.append(int(re.search(r'\d+', s[0]).group()))
else:
winOrder.append(0)
hwnd = titles[winOrder.index(max(winOrder))][1]
#Get the edit window from inside the Word instance
def callback(hwnd, hwnds):
if win32gui.GetClassName(hwnd) == '_WwG':
hwnds.append(hwnd)
#I think there should be a 'return False' here to let EnumChildWindows
#know it doesn't have to keep looping once it finds the edit window,
#but it crashes with 'pywintypes.error: (0, 'EnumChildWindows',
#'No error message is available') if I try that
return True
hwnds = []
win32gui.EnumChildWindows(whndl, callback, hwnds)
#Something like this...
#window = win32gui.AccessibleObjectFromWindow(hwnds[0])
那么现在 - 如何从 Windows 句柄创建 COM 对象?