我正在使用宏在 excel 中使用命名范围中的文本填充 Word 文档。Word 文档具有与命名的 Excel 区域对应的书签。我没有编写代码,而是从另一个来源复制它。
这个宏比我发布的片段要多得多。如果有用,我可以发布其余的。我有大约一半的Word文档已添加书签,并且宏工作正常,然后突然停止工作。
我在下面突出显示的行中收到错误 1004。我是新手,所以我什至不太确定我应该搜索什么来解决这个问题。您能提供的任何帮助将不胜感激!提前感谢!
附言如果相关,我正在使用 Word 和 Excel 2007
'PASTE TEXT STRINGS LOOP
n = 1
For Each temp In BkmTxt
p = p + 1
Prompt = "Please wait. Copying text. Carrying out operation " & p & " of " & pcount & "."
Application.StatusBar = Prompt
'If The Bkmtxt(n) is empty then go to the next one, once that has been found do next operation.
If BkmTxt(n) = Empty Then
n = n + 1
'should find match and work
Else
'You might want to use multiple copies of the same text string.
'In this case you need to call the bookmark as follows: "ARTextWhatever_01"
'You can use as many bookmarks as you want.
BkmTxtSplit = Split(BkmTxt(n), "_")
vValue = Range(BkmTxtSplit(0)).Text **<----- ERROR HERE**
Set wdRng = wdApp.ActiveDocument.Bookmarks(BkmTxt(n)).Range
If Len(sFormat) = 0 Then
'replace the bookmark text
wdRng.Text = vValue
Else
'replace the bookmark text with formatted text
wdRng.Text = Format(vValue, sFormat)
End If
'Re-add the Bookmark
wdRng.Bookmarks.Add BkmTxt(n), wdRng
n = n + 1
End If
Next
第 1 步:不要从外部源复制代码。使用外部资源作为学习工具,并尝试了解他们实际在做什么。
现在,如果我理解正确,您只需要一个带有命名范围的 Excel 工作表,我假设它们中已经有信息,还有一个带有与命名范围完全匹配的书签的 Word 文档:
步骤 2:确保在 excel 中具有单词对象库引用
这里:
sub KeepItDoin()
dim xlRange as Excel.Range
dim wdApp as new Word.Application
dim wdDoc as Word.Document
dim wdBkm as Word.Bookmark
set wdDoc = wdApp.Documents.Open( "Filepath" ) 'get filepath from where ever
for each wdBkm in wdDoc.Bookmarks
set xlRange = Application.Range(wdBkm.Name)
wdBkm.range.text = xlRange.Value
next wdBkm
end sub
这可能会让你接近(没有测试,不在乎它是否有效。用它来学习)。这个想法是,如果书签与范围匹配,我们可以使用它们的名称在 excel 中查找范围,然后告诉 excel 将其中的数据移动到书签范围内。
您可能需要添加一些格式,或者创建一个表格,然后在范围内逐个单元格移动并填充表格,但这与我愿意得到的一样接近,因为您喜欢复制意大利面。
如果有人感兴趣,我想通了。我插入到Word文档中的书签出错。如果 Word 文档包含与 excel 中的范围不对应的书签,则此宏将返回错误 1004。谢谢你的帮助。