4

Access データベースのメモ フィールドから RTF テキストを VBA を使用して Word 文書にコピーする方法はありますか。私は現時点でこのコードを持っていますが、html テキストを生成します (テキストにはタグが含まれており、フォーマットされていません)。

' 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

これを行う他の方法はありますか?

4

1 に答える 1

6

メモ型フィールドの「リッチ テキスト」オプションでは、書式設定されたテキストが 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
于 2013-05-03T08:31:28.790 に答える