加载带有可变文件名的XML文件,以便使用XSL进行转换

时间:2015-11-06 18:42:49

标签: xml excel vba excel-vba xslt

我希望在Excel VBA中运行以下命令:

Dim xmldoc As Object, xsldoc As Object, newdoc As Object

Set xmldoc = CreateObject("MSXML2.DOMDocument")
Set xsldoc = CreateObject("MSXML2.DOMDocument")
Set newdoc = CreateObject("MSXML2.DOMDocument")

' LOAD XML
xmldoc.async = False
xmldoc.Load ActiveWorkbook.Path & "\Original.xml"  

' LOAD XSL
xsldoc.async = False
xsldoc.Load ActiveWorkbook.Path & "\XSLT_File.xsl"

' TRANSFORM
xmldoc.transformNodeToObject xsldoc, newdoc
newdoc.Save ActiveWorkbook.Path & "\Output.xml"

我在相同的代码中运行它,但之后是步骤,而原始XML是导出的

ActiveWorkbook.SaveAsXMLData xmlDirName & fileName & ".xml", objMapToExport

其中“filename”是执行保存时的时间戳。

如何重写LOAD XML VBA,以便它知道加载刚刚在代码中创建的XML?

1 个答案:

答案 0 :(得分:1)

只需将导出的XML文件名作为参数传递给运行XSLT转换的子例程或函数,假设这两个过程都在同一个工作表或同一模块之后。

Public Sub XMLExport()
    ...rest of code...

    ActiveWorkbook.SaveAsXMLData xmlDirName & fileName & ".xml", objMapToExport

    Call XSLTransformation(xmlDirName & fileName & ".xml")   

End Sub


Public Sub XSLTransformation(strfile As String)
   Dim xmldoc As Object, xsldoc As Object, newdoc As Object

   Set xmldoc = CreateObject("MSXML2.DOMDocument")
   Set xsldoc = CreateObject("MSXML2.DOMDocument")
   Set newdoc = CreateObject("MSXML2.DOMDocument")

   ' LOAD XML
   xmldoc.async = False
   xmldoc.Load strfile   ' <------  CHANGE HERE

   ' LOAD XSL
   xsldoc.async = False
   xsldoc.Load ActiveWorkbook.Path & "\XSLT_File.xsl"

   ' TRANSFORM
   xmldoc.transformNodeToObject xsldoc, newdoc
   newdoc.Save ActiveWorkbook.Path & "\Output.xml"
End Sub