总结一下我正在尝试做什么,我为一个非营利组织工作,当有人向我们捐款时发出确认信(基本上谢谢你)。我们每个月都有多个不同的信件,并发送到IS进行“处理”。我想让它变得高效并且尽可能少地使用IS,所以我在VB.NET中创建了一个程序,它使用Word书签将内容粘贴到模板中,在SQL中更新表格以便可以使用实时数据测试信件,并向生产部门发送电子邮件,让他们知道测试信件。它完全有效,除了......
当我将内容插入到字母模板中时,我不能为我的生活弄清楚如何保留RTF(RichText)。
我已经尝试将RichTextBox的内容保存为RTF文件,但我无法弄清楚如何将RTF文件内容插入到我的文档模板中并替换书签。
我已经尝试过使用Clipboard.SetText,odoc ......粘贴方法,但它不可靠,因为我无法准确说明我希望粘贴文本的位置。查找/替换功能不是很有用,因为我试图替换的所有书签都在文本框中。
我会显示一些代码,但大多数代码都因为不工作而被删除了。无论哪种方式,这里有一些我一直在使用的代码:
Private Sub testing()
strTemplateLocation = "\\SERVER\AcknowledgementLetters\TEST\TEMPLATE.dot"
Dim Selection As Word.Selection
Dim goWord As Word.Application
Dim odoc As Word.Document
goWord = CreateObject("Word.Application")
goWord.Visible = True
odoc = goWord.Documents.Add(strTemplateLocation)
Clipboard.Clear()
Clipboard.SetText(txtPreD.Rtf, TextDataFormat.Rtf)
odoc.Content.Find.Execute(FindText:="<fp>", ReplaceWith:=My.Computer.Clipboard.GetText)
'Code for looping through all MS Word Textboxes, but didn't produce desired results
For Each oCtl As Shape In odoc.Shapes
If oCtl.Type = Microsoft.Office.Core.MsoShapeType.msoTextBox Then
oCtl.TextFrame.TextRange.Text.Replace("<fp>", "Test")
goWord.Selection.Paste()
End If
Next
'Clipboard.Clear()
'Clipboard.SetText(txtPostD.Rtf, TextDataFormat.Rtf)
'odoc.Content.Find.Execute(FindText:="<bp>", ReplaceWith:="")
'goWord.Selection.Paste()
MsgBox("Click Ok when finished checking.")
odoc.SaveAs2("\\SERVER\AcknowledgementLetters\TEST\TEST.docx")
odoc = Nothing
goWord.Quit(False)
odoc = Nothing
goWord = Nothing
End Sub
...这是设置书签的默认代码。只要不需要格式化,这就完美无缺:
Private Sub SetBookmark(odoc As Object, strBookmark As String, strValue As String)
Dim bookMarkRange As Object
If odoc.Bookmarks.Exists(strBookmark) = False Then
Exit Sub
End If
bookMarkRange = odoc.Bookmarks(strBookmark).Range
If ((Err.Number = 0) And (Not (bookMarkRange Is Nothing))) Then
bookMarkRange.text = strValue
odoc.Bookmarks.Add(strBookmark, bookMarkRange)
bookMarkRange = Nothing
End If
End Sub
TL; DR - 需要格式化文本(例如:“TEST”)作为书签或替换文本插入到Word文档中。
预期结果:将“fp”(首页)书签替换为“TEST”,包括粗体格式。实际结果:“fp”未替换(使用剪贴板和查找/替换方法时),或者替换为“TEST”而没有格式化。
我想到了!我不得不做一个奇怪的方式,但它的工作原理。
以下代码将RichTextBox保存为.rtf文件:
RichTextBoxName.SaveFile("temp .rtf file location")
然后我使用以下代码将.rtf文件插入书签:
goWord.ActiveDocument.Bookmarks("BookmarkName").Select()
goWord.Selection.InsertFile(FileName:="temp .rtf file location")
然后我删除了临时文件:
If My.Computer.FileSystem.FileExists("temp .rtf file location") Then
My.Computer.FileSystem.DeleteFile("\temp .rtf file location")
End If