如何在vba中任意创建xml文件?

xml文件是拥有xml代码的文件。

如下是一个xml代码:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

如果要将上述代码保存为xml文档,可以使用ADODB.Stream对象将xml代码写入流后另存为文件,

代码如下:

Sub QQ1722187970()
    Dim sXml As String
    sXml = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
    "<note>" & _
    "<to>George</to>" & _
    "<from>John</from>" & _
    "<heading>Reminder</heading>" & _
    "<body>Don't forget the meeting!</body>" & _
    "</note>"
    Const adTypeBinary = 1
    Const adTypeText = 2
    Const adModeRead = 1
    Const adModeWrite = 2
    Const adModeReadWrite = 3
    Const adSaveCreateOverWrite = 2
    Dim oStream As Object
    '创建流对象
    Set oStream = CreateObject("ADODB.Stream")
    With oStream
    '打开流
    .Open
    '设置为文本模式
    .Type = adTypeText
    .Charset = "utf-8"
    '写入xml代码
    .WriteText sXml
    '另存为当前路径下的文件,adSaveCreateOverWrite参数表示如果存在源文件,则覆盖
    .SaveToFile "test.xml", adSaveCreateOverWrite
    '关闭流对象
    .Close
    End With
End Sub

 

       

发表评论