如何使用Word VBA编辑HTML文件XMLHTTP对象

问题描述:

我在写一个Word VBA宏,最终创建一个等效的HTML文件。在创建这个HTML文件后,我想将它的纯HTML代码放入一个字符串中以供进一步编辑(在同一个宏脚本中)。我处理的所有文件都通过HTTP请求访问本地服务器,而不是本地驱动器。 下面是一些代码,我有:如何使用Word VBA编辑HTML文件XMLHTTP对象

...{other code}... 
Dim httpreq as Object 
Dim htmlread as String 
Set httpreq = CreateObject("MSXML.XMLHTTP") 
...{other code}... 
ActiveDocument.SaveAs2 FileName := HTMLFilePath, FileFormat: wdFormatFilteredHTML 
httpreq.Open "POST", HTMLFilePath, False 
httpreq.send 
htmlread = httpreq.responseText 

..{htmlread string is modified using VBA methods like Replace}... 

如何覆盖使用HTTP方法修改后的字符串HTMLFilePath文件?

对于微软Office的最新版本中,你可以使用Microsoft XML, v 6.0Microsoft HTML Object Library

在VBA窗口中,选择Tools -> References -> Microsoft XML, v 6.0Tools -> References -> Microsoft HTML Object Library

试试下面的代码:

Sub parse() 
Dim http As New MSXML2.XMLHTTP60 
Dim html As New HTMLDocument 
Dim htmlread As String 

With CreateObject("MSXML2.serverXMLHTTP") 
    .Open "GET", "http://www.google.com", False 
    .send 
    htmlread = .responseText 
End With 

html.body.innerHTML = htmlread 'raw full source code 
Debug.Print html.body.innerHTML 

'..{htmlread string is modified using VBA methods like Replace}... 

html.body.innerHTML = htmlread 'edited source code 
Debug.Print html.body.innerHTML 

Set html = Nothing 
End Sub 
+0

感谢,还怎么做我上传/保存更新的文档到服务器上的实际文档? – Steven

+0

@Steven如果你要将它保存在本地驱动器中,你可以将它保存为像'ActiveDocument.SaveAs Filename:= path FileFormat:= xlHtml'这样的html文件。但事情并不那么简单。我不是这方面的专业人士,但任何图像,C​​SS文件,其他附件等也应保存。但是,如果要将其上载到服务器,则无需这样做。就我所知,您可以[通过FTP将文件传输到服务器](https://officetricks.com/ftp-server-file-transfer-with-excel-macro/)。 – Tehscript