从特殊的Excel范围创建XML

时间:2018-07-20 13:07:17

标签: xml excel vba

我需要使用周期直到L1和L2列中的最后一个单元格来填充来自特定excel列的XML。

例如,我将信息存储在2个excel工作表列中:

L1值1值2值3

L2 值1a 值2a Value3a

我期望的XML输出:

<Fields Count="6">
<Field Name="L1-1">Value1</Field>
<Field Name="L1-2">Value2</Field>
<Field Name="L1-3">Value3</Field>
<Field Name="L2-1">Value1a</Field>
<Field Name="L2-2">Value2a</Field>
<Field Name="L2-3">Value3a</Field>
<Fields/>

应该是某种循环。同样,计数值也非常适合基于总数进行计算。

1 个答案:

答案 0 :(得分:0)

如下所示,例如

Option Explicit
Public Sub TestXML()
    Dim Xmldoc As MSXML2.DOMDocument60, strXML As String, loopRange As Range, count As Long, i As Long, j As Long
    Set loopRange = ActiveSheet.Range("A1:B4")
    count = loopRange.count - loopRange.Columns.count
    strXML = vbNullString
    strXML = "<Fields Count=" & Chr$(34) & count & Chr$(34) & ">"
    For j = 1 To loopRange.Columns.count
        For i = 2 To loopRange.Rows.count
            strXML = strXML & "<Field Name=""" & loopRange.Columns(j).Cells(1) & "-" & i - 1 & """>" & loopRange.Cells(i, j) & "</Field>"
        Next i
    Next j
    strXML = strXML & "</Fields>"

    Set Xmldoc = New MSXML2.DOMDocument60
    Xmldoc.LoadXML strXML

    Debug.Print Xmldoc.DocumentElement.Text
    Debug.Print Xmldoc.SelectNodes("//Field").Length

End Sub

数据布局:

Data