Copy RTF text from Access to word table using VBA

后端 未结 1 1130
我在风中等你
我在风中等你 2020-12-18 10:27

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 include

相关标签:
1条回答
  • 2020-12-18 10:30

    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.

    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:\Users\Public\zzzTest.rtf", 6  ' 6 = wdFormatRTF
        objWord.Quit
        Set objWord = Nothing
        Set fso = Nothing
    End Sub
    
    0 讨论(0)
提交回复
热议问题