比方说,我有一个页面,如下所示,保存在C:\ TEMP \ html_page.html:读取和操作HTML与Excel VBA
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="xxx1">
<img src="test.png">
</div>
</body>
</html>
我想以编程方式调整IMG src属性,基于Excel数据& VBA。基本上可以通过Xpath找到div,并调整其中包含的(单个)img标记。
我发现了一个使用VBA通过XML库here操作XML的示例,但我一直在讨论如何使用HTML对象库进行此项工作;找不到任何示例和/或文档。
Dim XDoc As Object, root As Object
Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
If XDoc.Load(html_path) Then
Debug.Print "Document loaded"
Else
Dim strErrText As String
Dim xPE As MSXML2.IXMLDOMParseError
' Obtain the ParseError object
Set xPE = XDoc.parseError
With xPE
strErrText = "Your XML Document failed to load" & _
"due the following error." & vbCrLf & _
"Error #: " & .ErrorCode & ": " & xPE.reason & _
"Line #: " & .Line & vbCrLf & _
"Line Position: " & .linepos & vbCrLf & _
"Position In File: " & .filepos & vbCrLf & _
"Source Text: " & .srcText & vbCrLf & _
"Document URL: " & .URL
End With
MsgBox strErrText, vbExclamation
所有我想要做的是:
'...
Set outer_div = XDoc.SelectFirstNode("//div[id='xxx1'")
... edit the img attribute
但我不能加载HTML页面,因为它不是正确的XML(img标签未闭)。
任何帮助,非常感谢。哦,我不能使用其他语言,比如Python,无赖。
非常感谢!似乎我几乎在那里:问题不是100%准确。我正在寻找适用于多行HTML文件的解决方案。我试图找到如何调整代码,但尚未成功。你介意加入这个答案吗? – MattV
@MattV,抱歉,我一定错过了一些东西,为什么这不适用于多行文件?让我知道,我会更新 – SWa