我想从XML文件中删除节点,并将其重写为练习以练习VBA,但是由于某种原因,appendCHild命令返回错误438。由于我没有编程经验,因此很难找到原因,为什么已经尝试从元素,节点,节点列表中更改变量的类型
Dim vFolder As String, vFile As String, vFileName As String
Dim vLineFile As Integer, vLineTAG As Integer, vLineResource As Integer
Dim vRange As String, vNode As String, vRange2 As String
Dim vWindowMain As String, vWindowFile As String, vWindowXML As String, vXMLSheetName As String
Dim XDoc As Object
Dim myNodes As IXMLDOMNodeList, myChildNodes As IXMLDOMNodeList
Dim myElement As IXMLDOMElement
Dim myNode As IXMLDOMNode, myChildNode As IXMLDOMNode
Dim NameItem As IXMLDOMAttribute
Dim nNode As Integer
Dim nChildNode As Integer
Dim wb As Workbook
Dim ws As Worksheet
'Remember to delete variables not used after
vWindowMain = ActiveWorkbook.Name
'Sheet that has received the nodes
Sheets("Plan1").Select
vRange = "A1"
vXMLSheetName = Range(vRange).Value + "Orionv5.xlsx"
Workbooks.Open vXMLSheetName, UpdateLinks:=False
vWindowXML = ActiveWorkbook.Name
vLineFile = 2
'main workbook
Windows(vWindowMain).Activate
Sheets("Plan1").Select
vRange = "A1"
vFolder = Range(vRange).Value
vLineTAG = 2
Do While True
Application.ScreenUpdating = False
vLineFile = vLineFile + 1
Windows(vWindowMain).Activate
Sheets("Plan1").Select
vRange = "A" + Trim(Str(vLineFile))
vFile = Range(vRange).Value
vFileName = vFolder + "\" + vFile 'xml arquives are listed on the main workbook
If vFile = "" Then
Exit Do
End If
Set XDoc = CreateObject("MSXML2.DOMDocument")
Set wb = Workbooks(vWindowXML)
Set ws = wb.Worksheets(1)
XDoc.async = False: XDoc.validateOnParse = False
XDoc.load (vFileName)
Set myNodes = XDoc.SelectNodes("//data")
For nNode = 0 To myNodes.Length - 1 'erasing all the "data" nodes
Set myNode = myNodes(nNode)
myNode.ParentNode.RemoveChild myNode
XDoc.Save vFileName
Next nNode
Do While True
With ws
vRange2 = "B" + Trim(Str(vLineTAG))
Set myNode = XDoc.SelectSingleNode("//root")
Set myElement = XDoc.createElement("data")
myNode.appendChild (myElement) 'not working
Set myNode = XDoc.SelectSingleNode("//root/data[vLineTAG]")
Set myChildNode = XDoc.createAttribute("name")
myChildNode.Text = .Range(vRange2).Value
myNode.Attributes.setNamedItem (NameItem) 'this will put the attribute name =""
vRange2 = "C" + Trim(Str(vLineTAG))
Set myNode = XDoc.SelectSingleNode("//data[vLineTAG]")
Set myChildNode = XDoc.createElement("value") 'putting a new node under the data node named value
myChildNode.Text = .Range(vRange2).Value
myNode.appendChild (myChildNode)
vRange2 = "A" + Trim(Str(vLineTAG))
XDoc.Save vFileName
vLineTAG = vLineTAG + 1
If .Range(vRange2).Value <> vFile Then
Exit Do
End If
End With
Loop
Loop
End Sub
在第一个appendChild调用中,它已经停止运行,并且我不知道是否有更多错误,也不是这是编辑XML文件的最佳方法,但现在对我来说很有意义。有人可以告诉我此错误的错误是什么吗?