我正在循环遍历我的节点列表并在单元格中植入值,向计数器变量添加一个并重复直到循环结束...
For Each n In myXML.SelectNodes("//a")
.Cells(X, 2).Value = n.Attributes.getNamedItem("href").Text
X = X + 1
Next n
有几千行有点慢,所以我想知道是否有更简单的方法吗?也许通过将列表放入数组然后转置数组?不太确定从哪里开始,但看到最后一行的想法:/
下面的完整工作代码
Sub gogo()
Dim theXMLstring As String
Dim theXMLdocument As New MSXML2.DOMDocument60
Dim n As MSXML2.IXMLDOMNode
Dim i As Long
theXMLstring = "<table><a href=""no"">hi</a><a href=""yes"">bye</a><a href=""WOAH"">woah</a></table>"
theXMLdocument.LoadXML (theXMLstring)
For Each n In theXMLdocument.SelectNodes("//a")
MsgBox (n.Attributes.getNamedItem("href").Text)
Next n
End Sub
我真正想要的是MyArr() = theXMLdocument.SelectNodes("//a").Attributes.getNamedItem("href").Text
答案 0 :(得分:2)
我不习惯使用XML,但我很确定只是优化工作表编写会产生巨大的差异(UI与内存中):
Dim arr()
For Each n In myXML.SelectNodes("//a")
x=x+1
ReDim Preserve arr(1 to x)
arr(x) = n.Attributes.getNamedItem("href").Text
Next n
Cells(1,1).Resize(x).Value=WorksheetFunction.Transpose(arr)
编辑:虽然ReDim
优化对单一范围分配来说是次要的,但我发布了建议的优化:
Dim arr(), nodes, i As Long
Set nodes = myXML.SelectNodes("//a")
ReDim arr(1 To nodes.Length, 1 To 1)
For i = 1 To nodes.Length
arr(i, 1) = nodes(i - 1).Attributes.getNamedItem("href").Text
Next
Cells(1, 1).Resize(nodes.Length).Value = arr