我想寫一個Excel VBA腳本來選擇性地從xml文件中獲取信息並用該信息製作一個表格。VBA XML讀取節點,如果屬性= 1,則讀取該節點中的其他屬性。對所有節點都這樣做
有數千個節點全名缺陷,每個缺陷都有屬性。 我想在每個缺陷中使用一個屬性來過濾一些不需要的缺陷,並且希望的缺陷列出名爲defect的所有其他屬性。
請參閱下面的更多信息。 nextSibling不能使用。
XML結構:
<!-- language: xml -->
<?xml version="1.0" encoding="WINDOWS-1252"?>
<CDXML>
<DATA><FaceInformation><Defects>
<Defect>
<Black Type="Integer" Value="1"/>
<Dots Type="Integer" Value="21"/>
<Height Type="Integer" Value="1"/>
</Defect>
<Defect>
<Black Type="Integer" Value="0"/>
<Dots Type="Integer" Value="22"/>
<Height Type="Integer" Value="2"/>
</Defect>
<Defect>
<Black Type="Integer" Value="1"/>
<Dots Type="Integer" Value="23"/>
<Height Type="Integer" Value="3"/>
</Defect>
</Defects></FaceInformation></DATA>
所需的輸出:
<!-- language: lang-none -->
Black Dots Height
1 21 1
1 22 3
VBA:
<!-- language: lang-vb -->
Dim xmlDoc As DOMDocument30
Set xmlDoc = New DOMDocument30
xmlDoc.async = False
Dim n, m As IXMLDOMNode
Dim j As Integer
XMLFileName = C:\1.xml
xmlDoc.Load (XMLFileName)
'This goes through all the attributes with the name Black,
'this is okay since Black only appear once in each node called defect.
For Each n In xmlDoc.SelectNodes("//Defects/Defect/Black")
'Read value of the Black attribute
Black = n.Attributes.getNamedItem("Value").Text
If Black <> "0" Then 'Print if 1
Cells(j + 3, 2) = Black
'I can not use nextSibling because the order of defects is not always the same
For Each m In n.SelectNodes("DefectClass")
Dots = m.Attributes.getNamedItem("Value").Text
'I have no idea what to do from this point
Cells(i + 3, 3) = Dots
Next
j = j + 1
End If
Next
對我來說顯得有些錯字的錯誤,如'XMLFileName = C:\ 1.XML '應該是引號內的'「XMLFileName = C: \ 1.xml 「'。進一步'Dim xmlDoc As DOMDocument30'給我的excel 2007系統編譯器錯誤。如果我使它成爲'DOMDocument60',這是可以接受的。我看着堆棧溢出舊帖子,並發現一個由@David Zemens相關和有趣。從他的計劃中獲取線索,我希望你能夠繼續下去。 –
skkakkar