在pywin32中将VBA With语句转换为Python



我正试图将VBA中的With语句转换为Python,更具体地说,这一个(用于MS Word):

With Selection.FormFields(1)
.Name = "Widget_name"
.EntryMacro = ""
.ExitMacro = ""
.Enabled = True
.OwnHelp = False
.HelpText = ""
.OwnStatus = False
.StatusText = ""
With .TextInput
.EditType Type:=wdRegularText, Default:="ComboBoxEdit", Format:= _
""
.Width = 0
End With
End With

我正在尝试编辑给定书签(Widget_name)的值并将其值更新为"ComboBoxEdit"

我有点不知道如何在Python中做到这一点。

例如,我是否也使用with?之后的.xxx = yyy怎么办?

我很天真地尝试了这个,但这轻轻地告诉你Name不是一个参数;)

with word.Selection.FormFields(1, Name="Widget_name"):
...

感谢

实际上,您可能不必使用等价的With语句。

下面的函数正在更新一些表单(并更新整个文档以匹配更改)。


from pathlib import Path
from typing import Dict, List, Union
import win32com.client as win32
def update_bookmarks(path: Union[Path, str], new_values: Dict[str, str]) -> List[str]:
"""Update Bookmarks if a given document and return names of updated forms"""
word = win32.gencache.EnsureDispatch("Word.Application")  # type: ignore
doc = word.Documents.Open(str(Path(path).absolute()))
doc.Activate()
# We will select the whole document to be sure to get all the forms
selection = word.Selection
selection.WholeStory()
updated: List[str] = []
for field in word.Selection.FormFields:
name = field.Name
current_value = field.TextInput.Default
value = new_values.get(name, None)
if value and value != current_value:
field.TextInput.Default = value
updated.append(name)
# If we have updated at least one form, we will update the whole document
# And then we will select just this last form to keep it clean
if updated:
selection.WholeStory()
selection.Fields.Update()
selection.Collapse()
return updated

new_values = {"Widget_name": "SuperWidget15"}
update_bookmarks(output_path, new_values)

最新更新