获取以下宏脚本的错误。需要在单个表中提取日期,名称和地址。由于日期只有一个值,因此第二个值返回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>
答案 0 :(得分:1)
尝试在桌面的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
答案 1 :(得分:0)
已经给出了更好的答案,但这是一个变种:
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:\Users\User\Desktop\random.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