我正在使用Excel电子表格中的文字更新word文档。
我从阅读帖子中了解到,如果您使用bookmark.text =“xx”更改书签中的文本,则删除书签,您必须将其重新添加。但是我无法这样做因为我不能设置要添加的书签的范围。
我尝试使用下面的代码,但得到运行时错误13 - 类型不匹配。有人可以让我知道我做错了吗?
Sub ChangeBMtext()
Dim WordApp As Object
Dim WordDoc As Object
Dim FileName As String
Dim ARange As Range
FileName = "C:\Drafts\Quick Test"
Set WordApp = CreateObject("word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(FileName)
If WordDoc.Bookmarks.Exists("InDocText") Then
Set ARange = WordDoc.Bookmarks("InDocText").Range
WordDoc.Bookmarks("InDocText").Range.Text = "add this text"
WordDoc.Bookmarks.Add Name:="InDocText", Range:=ARange
End If
End Sub
答案 0 :(得分:1)
我在其他地方找到了答案。这段代码完美无缺:
Sub ChangeBMtext()
Dim WordApp As Object
Dim WordDoc As Object
Dim strBMName As String
Dim objBMRange As Object
FileName = "C:\Drafts\Quick Test"
Set WordApp = CreateObject("word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(FileName)
If WordDoc.Bookmarks.Exists("InDocText") Then
strBMName = "InDocText"
Set objBMRange = WordDoc.Bookmarks(strBMName).Range
objBMRange.Text = "add this text"
WordDoc.Bookmarks.Add Name:=strBMName, Range:=objBMRange
Set objBMRange = Nothing
End If
End Sub