使用 VBA 将 RTF 文本从 Access 复制到 word 表 [英] Copy RTF text from Access to word table using VBA
问题描述
有没有办法使用 VBA 将 RTF 文本从 Access 数据库中的备注字段复制到 Word 文档.我现在有这个代码,但它生成 html 文本(文本包含标签但没有格式化).
Is there a way to copy a RTF text from a memo field in Access Database to Word document using VBA. I have this code at the moment but it produces html text (the text includes tags and not formatted).
' Query the database and get the sales for the specified customer
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Sales WHERE Sales.[ID] ='" & Forms![customers]![id] & "'")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
' Create file and add rtf text
Set ts = fso.CreateTextFile("c: emp emp.rtf", True)
ts.Write rs(3)
ts.Close
' Add a row
doc.Tables(1).Rows.Add
' Get the number of the added row to add data
i = doc.Tables(1).Rows.Last.Index
' Add sale to word table
doc.Tables(1).Cell(i, 2).Range.InsertFile "C: emp emp.rtf", , False
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are not records in the recordset."
End If
MsgBox "Finished." & i
rs.Close
Set rs = Nothing
有没有其他方法可以做到这一点?
Is there any other way to do this?
推荐答案
请注意,备注字段的富文本"选项不会将格式化文本存储为 RTF.格式化文本存储为 HTML,这就是您在文本中看到 HTML 标签的原因.
Note that the "Rich Text" option for Memo fields does not store the formatted text as RTF. The formatted text is stored as HTML, which is why you were seeing HTML tags in your text.
以下 Access VBA 代码创建一个 Word 文档,其中包含格式化文本并保存为 .rtf
.如果您不承诺使用 RTF,则可以轻松修改代码以将文档保存为 .doc
或 .docx
.
The following Access VBA code creates a Word document that contains formatted text and is saved as .rtf
. If you're not committed to using RTF then the code could easily be modified to save the document as .doc
or .docx
.
Sub FormattedTextToWord()
Dim objWord As Object ' Word.Application
Dim fso As Object ' FileSystemObject
Dim f As Object ' TextStream
Dim myHtml As String, tempFileSpec As String
' grab some formatted text from a Memo field
myHtml = DLookup("Comments", "MyTable", "ID=101")
Set fso = CreateObject("Scripting.FileSystemObject") ' New FileSystemObject
tempFileSpec = fso.GetSpecialFolder(2) & "" & fso.GetTempName & ".htm"
' write to temporary .htm file
Set f = fso.CreateTextFile(tempFileSpec, True)
f.Write "<html>" & myHtml & "</html>"
f.Close
Set f = Nothing
Set objWord = CreateObject("Word.Application") ' New Word.Application
objWord.Documents.Add
objWord.Selection.InsertFile tempFileSpec
fso.DeleteFile tempFileSpec
' the Word document now contains formatted text
objWord.ActiveDocument.SaveAs2 "C:UsersPubliczzzTest.rtf", 6 ' 6 = wdFormatRTF
objWord.Quit
Set objWord = Nothing
Set fso = Nothing
End Sub
这篇关于使用 VBA 将 RTF 文本从 Access 复制到 word 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!