以下宏脚本出错。需要在单个表中提取日期,名称和地址。由于只有一个日期值,因此第二个值返回 null。
但是我需要在提取日期的所有记录中存在相同的值
Set ApplicationsNode = oXMLFile.SelectNodes("/Extract/Applications/Application")
Set extractnodes = oXMLFile.SelectNodes("/Extract/ExtractDate")
Set NameNode = oXMLFile.SelectNodes("/Extract/Applications/Application/Name/text()")
Set AddrNode = oXMLFile.SelectNodes("/Extract/Applications/Application/Addr/text()")
For i = 0 To (ApplicationsNode.Length - 1)
Extract = extractnodes(i).NodeValue
Name = NameNode(i).NodeValue
Addr = AddrNode(i).NodeValue
mainWorkBook.Sheets("Sheet1").Range("A" & i + 2).Value = Extract
mainWorkBook.Sheets("Sheet1").Range("C" & i + 2).Value = Name
mainWorkBook.Sheets("Sheet1").Range("D" & i + 2).Value = Addr
Next
输入 XML:
<Extract>
<ExtractDate>2018-02-21 10:01:01</ExtractDate>
<Applications>
<Application>
<Name>1234</Name>
<Addr>700ST</Addr>
</Application>
<Application>
<Name>123466</Name>
<Addr>277AVD</Addr>
</Application>
<Applications>
</Extract>
尝试在桌面content.xml
文件中使用以下部分元素并运行以下代码。
在content.xml
文件中:
<Extract>
<ExtractDate>2018-02-21 10:01:01</ExtractDate>
<Applications>
<Application>
<Name>1234</Name>
<Addr>700ST</Addr>
</Application>
<Application>
<Name>123466</Name>
<Addr>277AVD</Addr>
</Application>
</Applications>
</Extract>
用于从以下位置分析值的脚本:
Sub DemoXML()
Dim post As Object
With CreateObject("MSXML2.DOMDocument")
.async = False: .validateOnParse = False
.Load (ThisWorkbook.path & "content.xml")
For Each post In .SelectNodes("//Extract//Application")
r = r + 1: Cells(r, 1) = post.ParentNode.ParentNode.FirstChild.Text
Cells(r, 2) = post.SelectNodes(".//Name")(0).Text
Cells(r, 3) = post.SelectNodes(".//Addr")(0).Text
Next post
End With
End Sub
填充结果:
2/21/2018 10:01 1234 700ST
2/21/2018 10:01 123466 277AVD
已经给出了更好的答案,但这里有一个变体:
Option Explicit
Public Sub DemoXML()
Dim post As Object, R As Long, C As Long, dateString As String
With CreateObject("MSXML2.DOMDocument")
.async = False: .validateOnParse = False
.Load "C:UsersUserDesktoprandom.xml"
dateString = .SelectSingleNode("//ExtractDate").Text
For Each post In .SelectNodes("//Application")
R = R + 1: Cells(R, 1) = dateString
Cells(R, 2) = post.FirstChild.Text
Cells(R, 3) = post.LastChild.Text
Next post
End With
End Sub