2015-12-14 22 views
1

我將Word文檔中的格式化文本複製到Access中的富文本字段中。如何將使用HTML的訪問格式的富文本轉換爲Word文檔

後來我想用VBA創建一個新的Word文檔,並將格式化後的文本寫入它。

問題是,Access使用HTML格式保存富文本。而當你試圖將其寫入文檔或docx時,你會看到文本及其HTML標籤。

如何將文本寫入Word文檔以保留預期的格式並且不顯示HTML代碼?

回答

2

我發現這個工作的唯一方法(不修改輸入字符串)是將HTML寫入臨時文件,然後使用.InsertFile將該文件加載到word文檔中。下面是一個接受輸入參數並將其放入新的Word文檔的子文件:

Sub WriteToWord(myHtmlFormattedText as String) 

    Dim objWord As Word.Application 
    Dim doc As Word.Document  
    Dim fso As Object ' FileSystemObject 
    Dim f As Object ' TextStream 
    Dim tempHtmlFile As String 

    ' Write your HTML content to a temp file: 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    tempHtmlFile = fso.GetSpecialFolder(2) & "\" & fso.GetTempName & ".htm" 

    Set f = fso.CreateTextFile(tempHtmlFile, True) 
    f.Write myHtmlFormattedText 
    f.Close 
    Set f = Nothing 
    Set fso = Nothing 


    ' Set up word object 
    Set objWord = CreateObject("Word.Application") 
    With objWord 
     .Visible = True 
     Set doc = .Documents.Add 
    End With 

    'Add HTML file contents: 
    objWord.Selection.InsertFile tempHtmlFile 

    ' Show the doc 
    doc.Activate 
End Sub 
+1

不錯。我認爲'tempFileSpec'應該是'tempHtmlFile'。 – Andre

+0

(cc:@Andre)是的。好答案。這是[我會建議](http://stackoverflow.com/a/16354580/2144390)。 ;) –

+0

哎。這就是'tempFileSpec'的來源。那麼,我認爲好的代碼或算法是程序員的傳說,代代相傳,不關心歸因或類似的事情。 @GordThompson – Andre

0

不知道這會幫助,但也有在Microsoft Word中的幾個不同的粘貼功能(在「首頁」標籤的你左上角),很多人忽視了

Paste Options

這可以讓你粘貼/無格式。不知道它是否會解決您的具體問題,但希望!

相關問題