2013-05-03 119 views
4

有沒有辦法使用VBA將RTF文本從Access數據庫中的備註字段複製到Word文檔中。我目前有這段代碼,但它會生成html文本(文本包含標籤並未格式化)。使用VBA將Access中的RTF文本複製到Word表格

' 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:\temp\temp.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:\temp\temp.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 

有沒有其他方法可以做到這一點?

+0

請輸入您當前輸出的示例。 – JohnFx 2013-05-03 05:13:51

回答

5

請注意,備註字段的「富文本」選項不會將格式化文本存儲爲RTF。格式化文本以HTML格式存儲,這就是您在文本中看到HTML標籤的原因。

以下Access VBA代碼創建一個包含格式文本的Word文檔並保存爲.rtf。如果您不承諾使用RTF,則可以輕鬆修改代碼以將文檔保存爲.doc.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

非常感謝。我能解決問題並將文件保存爲docx格式。 – 2013-05-06 02:43:55

相關問題