如何在保留格式的同时使用 Visual Basic 将 HTML 格式的字符串插入到 Microsoft Word 文档中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/161519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:27:01  来源:igfitidea点击:

How do I insert HTML-Formatted Strings into a Microsoft Word Document using Visual Basic while preserving formatting?

htmlvbams-word

提问by Jonathan Yee

I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (<b>, <i>, etc.). Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?

我使用 Visual Basic 和自动化接口从外部应用程序检索字符串。这些字符串包含简单的 html 格式代码(<b>、<i> 等)。Visual Basic for Word 中是否有任何简单的函数可以将这些字符串插入到 Word 文档中并将 html 格式代码转换为 Word 格式?

回答by Jonathan Yee

Here's a link to add HTML to the clipboard using VB:

这是使用 VB 将 HTML 添加到剪贴板的链接:

http://support.microsoft.com/kb/274326

http://support.microsoft.com/kb/274326

Once you have the HTML on the clipboard, paste it into your word doc using something like this:

在剪贴板上有了 HTML 后,使用以下内容将其粘贴到您的 word 文档中:

ActiveDocument.Range.PasteSpecial ,,,,WdPasteDataType.wdPasteHTML

This is pretty much the equivalent of you cutting and pasting it in manually.

这几乎相当于您手动剪切和粘贴它。

回答by Adam Law

Use InsertFile

使用插入文件

Set objdoc = objInsp.WordEditor
Set objword = objdoc.Application
Set objsel = objword.Selection
objsel.WholeStory
vs_html = "<html><body>" + vs_body + "</body></html>"
vs_file = "C:\temp.html"
Call DumptoFile(vs_file, "", vs_html, False)
RetVal = objsel.InsertFile(vs_file, , , False, False)

回答by Michael

I'm using 2016. The only thing that worked was Range.InsertFile(path). Pasting Special didn't work.

我正在使用 2016。唯一有效的是 Range.InsertFile(path)。粘贴特殊功能不起作用。

回答by Treb

AFAIK there is no builtin function to do that in VBA. You will have to write it yourself, which would be not too difficult if you restirct it to parse <b>, <i>, <a> and <p>,for example. All other tags would have to be ignored.

AFAIK 在 VBA 中没有内置函数可以做到这一点。您将不得不自己编写它,例如,如果您重新编译它,这将不会太困难<b>, <i>, <a> and <p>,。所有其他标签都必须被忽略。