从XML标记获取值到Excel工作表

时间:2014-05-08 08:47:04

标签: vba excel-vba excel

我对vba编码缺乏经验,需要将xml文件中的值拉到excel表。尝试在谷歌的帮助下编码,但没有成功。下面是我的xml文件

<CRD>
..
<PLAN>Plan01</PLAN>
..
</CRD>

以下是我测试过的代码:

代码1

Private Sub RunTest_Click()

Dim envFrmwrkPath As String
Dim objfso, app, Eval As Object

envFrmwrkPath = ActiveSheet.Range("E6").Value

Set EnvVarXML = CreateObject("Microsoft.XMLDOM")

EnvVarXML.Load (envFrmwrkPath & "CRD-0071709[1].xml")

For Each UIElement In EnvVarXML.SelectNodes("//CRD")
Set Field = Eval(objUIElement.SelectSingleNode("PLAN").Text)
Sheet1.Cells(2, 2).Value = Field
Next

End Sub

代码2

Sub ImportXMLtoList()

Dim xml_doc As New MSXML2.DOMDocument60
Dim onode As MSXML2.IXMLDOMElement
Dim chnode As MSXML2.IXMLDOMElement
Dim brtn As Boolean

brtn = xml_doc.Load("D:\Satheesh 244688\CI Team\Med D Formulary Testing\May 8th\CRD-0071709[1].xml")

'Set onode = xml_doc.SelectSingleNode("/CRD")

For Each onode In xml_doc.SelectSingleNode("//CRD")

nm = onode.nodeName
If nm = "RxPlanID" Then
Sheet1.Cells(2, 2) = chnode.Text
End If

Next

End Sub

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您将使用的xml是否如上所述,或者您是否将循环遍历多个节点。

使用下面的xml

<Root>
<Row>
<Name>John</Name>
</Row>
<Row>
<Name>Anne</Name>
</Row>
</Root>

和这个vba

Sub GetXML()
    Dim myXML As Object
    Dim myNodes As Object
    Dim myNode As Object
    Dim myRow As Integer

    'Create xml object
    Set myXML = CreateObject("MSXML2.DOMDocument.6.0")

    myXML.Load "c:\data.xml"     'Change for your file path

    'Check if valid XML
    If myXML.parseError <> 0 Then
        'Parse error, so show message
        MsgBox "Something went wrong loading XML!" & vbCrLf & vbCrLf & myXML.parseError.reason
        Exit Sub
    End If

    Set myNodes = myXML.SelectNodes("//Row")
    myRow = 1
    For Each myNode In myNodes
        Sheet1.Cells(myRow, 1) = myNode.SelectSingleNode("Name").Text
        myRow = myRow + 1
    Next myNode


End Sub

Puts&#34; John&#34;在单元格A1和&#34; Anne&#34;在Sheet1上的单元格A2中