Convert a Word Range to a String with HTML tags in VBA

巧了我就是萌 提交于 2019-12-11 06:32:34

问题


I have a Word document and I need to copy some paragraph of it into a string in VBA. When doing so, the text formatting must be converted to HTML tags. For example if my paragraph looks like this:

Hello I am Alice.

I want to get a string that contains:

Hello I am <b>Alice</b>

(And it would be great if it also work for bulleted list and other kind of formatting).

I am using Microsoft Visual Basic for Applications 7.0. I am new to VBA and a lot of code I found on Internet does not work for me because my version is old. Unfortunately, downloading a more recent version is not an option in my case.

Here is a code sample that works to convert a paragraph to a string without formatting:

Dim pParagraph As Paragraph
'... at some point, pParagraph is set to a paragraph of the document

Dim pRange As Range
Dim pString As String
Set pRange = ActiveDocument.Range(Start:=pParagraph.Range.Start, End:=pParagraph.Range.End - 1)
pString = Trim(pRange.Text)

I did some research on Internet and found the advise to copy the Range to the clipboard and to use Clipboard.getText. Unfortunately Clipboard.getText does not even compile for me.


回答1:


One way I know to get formatting in Word turned into html tags is to use Access. If you create an Access table with a field that has Long Text data type and Rich Text as the Text Format and import your Word text into it, when you query Access to put the Text back into Word it comes out as html tagged text.




回答2:


You could use code like the following as a starting point. Obviously, though, you'll have to extend it to handle all the tags you're concerned with.

Sub ApplyHTML()
Application.ScreenUpdating = False
With ActiveDocument.Range
  '.ListFormat.ConvertNumbersToText
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Format = True
    .Forward = True
    .MatchWildcards = True
    .Wrap = wdFindContinue
    .Font.Underline = True
    .Text = ""
    .Replacement.Text = "<u>^&</u>"
    .Execute Replace:=wdReplaceAll
    .ClearFormatting
    .Font.Bold = True
    .Replacement.Text = "<b>^&</b>"
    .Execute Replace:=wdReplaceAll
    .ClearFormatting
    .Font.Italic = True
    .Replacement.Text = "<i>^&</i>"
    .Execute Replace:=wdReplaceAll
    .ClearFormatting
    .Highlight = True
    .Replacement.Text = "<h>^&</h>"
    .Execute Replace:=wdReplaceAll
  End With
End With
Application.ScreenUpdating = True
End Sub


来源:https://stackoverflow.com/questions/53524539/convert-a-word-range-to-a-string-with-html-tags-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!