VBA导入XML无法提取PartNumber属性值,仅返回最后属性值求助
搞定Excel只取到XML最后一个属性的问题
嘿,我一眼就看到问题出在哪了——你的VBA代码在遍历XML属性的时候,一直在覆盖同一个单元格,最后自然只剩最后一个属性的值啦!咱们一步步来解决:
问题根源
看这段循环代码:
For Each myAtr In xmlNodePin.Attributes Sheets("WL-test1").Cells(y, x).Value = myAtr.Text Next myAtr
每遍历一个属性,就把值写到Cells(y,x),前面的属性值全被后面的覆盖了,直到最后一个UnitType处理完,单元格里当然就只剩它了。而且你的XPath写的@PartNumber只是筛选出有这个属性的节点,但你并没有直接提取它,反而遍历了所有属性,这完全没必要呀。
直接解决:精准提取PartNumber
最简单的方法就是跳过属性遍历,直接定位到你要的PartNumber属性。修改后的代码如下:
Set xmlNodeListPin = xmldoc.SelectNodes("//ConnectiveDevice[@Tag='" & ForDTRFromTag & "']/PinList/Pin[@Tag='" & ForDTRFromPinTag & "']/*/*/*/PartNumberList/PartNumber") On Error Resume Next For Each xmlNodePin In xmlNodeListPin ' 直接获取PartNumber属性的文本值 Sheets("WL-test1").Cells(y, x).Value = xmlNodePin.Attributes("PartNumber").Text x = x + 1 ' 移到下一列 myCheck = 0 Next xmlNodePin x = x + myCheck * (UBound(CableFrom) + 1) myCheck = 1
这里把XPath调整成选中PartNumber节点,然后直接通过属性名PartNumber获取值,一步到位,根本不需要遍历所有属性。
拓展:如果需要提取多个属性
要是之后你还想提取Description、Cost这些属性,就得给每个属性分配不同的单元格,避免覆盖。比如:
Set xmlNodeListPin = xmldoc.SelectNodes("//ConnectiveDevice[@Tag='" & ForDTRFromTag & "']/PinList/Pin[@Tag='" & ForDTRFromPinTag & "']/*/*/*/PartNumberList/PartNumber") On Error Resume Next For Each xmlNodePin In xmlNodeListPin ' 把不同属性放到不同列 Sheets("WL-test1").Cells(y, x).Value = xmlNodePin.Attributes("PartNumber").Text Sheets("WL-test1").Cells(y, x+1).Value = xmlNodePin.Attributes("Description").Text Sheets("WL-test1").Cells(y, x+2).Value = xmlNodePin.Attributes("Cost").Text x = x + 3 ' 根据提取的属性数量调整步长 myCheck = 0 Next xmlNodePin x = x + myCheck * (UBound(CableFrom) + 1) myCheck = 1
测试建议
你可以用自己写的Test宏生成测试XML,然后把修改后的代码加进去,用Debug.Print xmlNodePin.Attributes("PartNumber").Text在立即窗口看看是不是正确拿到了DTRxxxxxxxxxxx,确保没问题再写到Excel里。
内容的提问来源于stack exchange,提问作者aliciavika
相关产品推荐
相关产品推荐

