LibreOffice Writer Basic宏求助:为每个书签创建文本框报错
解决LibreOffice Writer宏中Bookmarks属性找不到的问题
问题根源
原代码的核心错误是文档对象获取错误:你将document赋值为ThisComponent.CurrentController.Frame,这是Writer的窗口框架对象,并非文档本身,因此不存在Bookmarks属性。正确的文档对象应该直接使用ThisComponent,它代表当前打开的Writer文档实例,包含Bookmarks集合。
修正后的宏代码
Sub CreateTextFramesForBookmarks() Dim document As Object Dim bookmarks As Object Dim bookmark As Object Dim textFrame As Object Dim textFrameProps As Object Dim anchorType As Integer ' 获取当前Writer文档对象 document = ThisComponent ' 获取文档中所有书签 bookmarks = document.Bookmarks ' 定义锚定类型:随字符嵌入文本流 anchorType = com.sun.star.text.TextContentAnchorType.AS_CHARACTER For Each bookmark In bookmarks ' 创建文本框对象 textFrame = document.createInstance("com.sun.star.text.TextFrame") ' 设置文本框内容为书签名称 textFrame.Text.String = bookmark.Name ' 设置文本框属性:锚定类型、大小 textFrameProps = textFrame.getPropertyValues( _ Array("AnchorType", "Width", "Height")) textFrameProps(0) = anchorType textFrameProps(1) = 1000 ' 宽度(单位:1/100mm) textFrameProps(2) = 500 ' 高度(单位:1/100mm) textFrame.setPropertyValues( _ Array("AnchorType", "Width", "Height"), textFrameProps) ' 将文本框插入到书签的起始位置 document.Text.insertTextContent(bookmark.Start, textFrame, False) Next bookmark End Sub
关键修改说明
- 文档对象修正:
document = ThisComponent直接获取当前文档,确保能访问Bookmarks属性。 - 锚定类型设置:使用
AS_CHARACTER锚定类型,让文本框随书签所在的文本一起排版,避免位置错乱。 - 文本框样式优化:添加基础宽高设置,避免文本框重叠或显示不全,你可以根据需求调整
Width和Height的数值(单位为1/100毫米)。 - 插入位置修正:通过
insertTextContent将文本框插入到书签的起始位置,确保每个文本框与对应书签精准关联。
内容的提问来源于stack exchange,提问作者Maaatth




