通过VBA

时间:2018-04-18 21:46:40

标签: xml excel vba excel-vba export

我一直在this question的答案中使用该模板,以便将Excel电子表格中的数据导出到每行的单独XML文件中。我已修改该帖子中的模板以匹配我需要的输出,但是当我运行宏时,我得到一个"运行时错误91:对象变量或者没有设置块变量。"这是我目前正在使用的VBA宏:

Sub xmlconverter1()

sTemplateXML = "<?xml version='1.0'?>" + vbNewLine + _
"<mods xmlns='http://www.loc.gov/mods/v3' xmlns:mods='http://www.loc.gov/mods/v3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xlink='http://www.w3.org/1999/xlink'>" + vbNewLine + _
    "   <titleInfo>" + vbNewLine + _
    "       <title></title>" + vbNewLine + _
    "   </titleInfo>" + vbNewLine + _
    "   <typeOfResource>" + vbNewLine + _
    "   </typeOfResource>" + vbNewLine + _
    "   <name type='personal'>" + vbNewLine + _
    "       <namePart></namePart>" + vbNewLine + _
    "   </name>" + vbNewLine + _
    "   <abstract>" + vbNewLine + _
    "   </abstract>" + vbNewLine + _
    "   <identifier>" + vbNewLine + _
    "   </identifier>" + vbNewLine + _
    "   <originInfo>" + vbNewLine + _
    "       <dateIssued></dateIssued>" + vbNewLine + _
    "   </originInfo>" + vbNewLine + _
    "   <physicalDescription>" + vbNewLine + _
    "       <form></form>" + vbNewLine + _
    "       <extent></extent>" + vbNewLine + _
    "   <subject>" + vbNewLine + _
    "       <geographic></geographic>" + vbNewLine + _
    "   </subject>" + vbNewLine + _
    "</mods>" + vbNewLine


 Set doc = CreateObject("MSXML2.DOMDocument")
 doc.async = False
 doc.validateOnParse = False
 doc.resolveExternals = False

 With ActiveWorkbook.Worksheets(1)
 lLastRow = .UsedRange.Rows.Count

For lRow = 2 To lLastRow
 sTitle = .Cells(lRow, 2).Value
 sType = .Cells(lRow, 11).Value
 sCreator = .Cells(lRow, 3).Value
 sDescription = .Cells(lRow, 6).Value
 sIdentifier = .Cells(lRow, 1).Value
 sDate = Format(.Cells(lRow, 9).Value, "YYYY-MM-DD")
 sForm = .Cells(lRow, 12).Value
 sExtent = .Cells(lRow, 22).Value
 sCoverage = .Cells(lRow, 7).Value
 doc.LoadXML sTemplateXML
 doc.getElementsByTagName("title")(0).appendChild doc.createTextNode(sTitle)
 doc.getElementsByTagName("typeOfResource")(0).appendChild doc.createTextNode(sType)
 doc.getElementsByTagName("name")(0).appendChild doc.createTextNode(sCreator)
 doc.getElementsByTagName("abstract")(0).appendChild doc.createTextNode(sDescription)
 doc.getElementsByTagName("identifier")(0).appendChild doc.createTextNode(sIdentifier)
 doc.getElementsByTagName("dateIssued")(0).appendChild doc.createTextNode(sDate)
 doc.getElementsByTagName("form")(0).appendChild doc.createTextNode(sForm)
 doc.getElementsByTagName("extent")(0).appendChild doc.createTextNode(sExtent)
 doc.getElementsByTagName("geographic")(0).appendChild doc.createTextNode(sCoverage)
 doc.Save sIdentifier

Next

 End With

End Sub

我能改变什么才能摆脱这个错误并仍然以我需要的格式给出输出?

1 个答案:

答案 0 :(得分:2)

doc.validateOnParse = False

隐藏了解析错误:

  

结束标记'mods'与开始标记'physicalDescription'不匹配。

您尚未关闭XML模板中的代码<physicalDescription>