更新时间:2023-02-23 16:58:18
当我将文本框添加到Word文档时,它们被添加到绘图画布中.因此,顶层形状是画布,并且文本框包含在画布中.您应该使用CanvasItems
方法访问画布中的对象,即文本框
When I add text boxes to a word document, they are added inside a drawing canvas. Therefore the top level shape is the canvas, and the text boxes are contained within the canvas. You should use the CanvasItems
method to access the objects in the canvas, ie the text boxes
以下示例对我有用.我用一个文本框创建了一个Word文档.
The following example works for me. I created a word document with a single text box.
import win32com.client
word = win32com.client.Dispatch("Word.Application")
canvas = word.ActiveDocument.Shapes[0]
for item in canvas.CanvasItems:
print item.TextFrame.TextRange.Text
更新:回答OP的评论.
我认为您的代码的问题在于,带有Find
的每一行代码都会创建一个新的Find
对象.您必须创建Find
对象并将其绑定到名称,然后修改其属性并执行它.因此,在您的代码中,您应该具有:
I think the problem with your code is that each line of code with Find
creates a new Find
object. You have to create and bind a Find
object to a name, then modify its attributes and execute it. So in your code you should have:
find = shp.TextFrame.TextRange.Find
find.Text = source
find.Replacement.Text = target
find.Execute(Replace=1, Forward=True)
或一行:
shp.TextFrame.TextRange.Find.Execute(FindText=source, ReplaceWith=target, Replace=1, Forward=True)
这两种方法都可以在我的测试代码中使用.
Both of these methods work in my test code.