前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VBA编写Ribbon Custom UI编辑器06——读取xml

VBA编写Ribbon Custom UI编辑器06——读取xml

作者头像
xyj
发布2020-08-20 10:15:32
1.2K0
发布2020-08-20 10:15:32
举报
文章被收录于专栏:VBA 学习VBA 学习

对Office文件读取和写入custom.xml,就是读取和写入ZIP文件,读取ZIP文件并解压缩可以查看前面文章VBA解压缩ZIP

读取custom.xml步骤:

  • 使用类模块CPKZip的功能,将custom.xml读取并解压
  • 然后转换编码
  • 再使用类模块CXML对数据进行处理
  • 最后输出到Excel
代码语言:javascript
复制
Private Const CUSTOMUI_NAME As String = "customUI/customUI.xml"

'从ZIP文件中读取customUI.xml
Sub ReadCustomUI()
    If VBA.Len(FileName) = 0 Then
        FileName = SelectFile()
        If VBA.Len(FileName) = 0 Then Exit Sub
    End If
    
    Dim zip As CPKZip
    Set zip = NewCPKZip()
    
    Dim ret As String
    ret = zip.Parse(FileName)
    If VBA.Len(ret) Then
        MsgBox ret
        Exit Sub
    End If
    
    Dim b() As Byte
    Dim bucs2() As Byte
    Dim sXML As String
    
    '尝试读取文件中的customUI.xml
    ret = zip.UnZipFile(CUSTOMUI_NAME, b)
    If ret = "zip: ZIP文件中不存在的文件:customUI/customUI.xml" Then
        '不存在的时候插入一个默认模板
        If MsgBox("文件中没有customUI.xml,是否插入一个模板?", vbYesNo) = vbYes Then
            sXML = "<customUI xmlns=""http://schemas.microsoft.com/office/2006/01/customui""  onLoad=""RibbonUI_onLoad"">" & _
                   "<ribbon>" & _
                    "<tabs>" & _
                    "  <tab id=""TabID"" label=""tabName"" insertAfterMso=""TabDeveloper"">" & _
                    "    <group id=""GroupID"" label=""GroupName"">" & _
                    "      <button id=""Button1"" label=""buttonname&#13;"" size=""large"" onAction=""Macro"" imageMso=""HappyFace"" />" & _
                    "    </group>" & _
                    "  </tab>" & _
                    "</tabs>" & _
                    "</ribbon>" & _
                    "</customUI>"
            
        Else
            Exit Sub
        End If
    Else
        '将读取到customUI.xml Byte数组,编码UTF8转换为UCS2
        ret = FromUTF8(b, bucs2)
        If VBA.Len(ret) Then
            MsgBox "编码转换出错:" & vbNewLine & ret
            Exit Sub
        End If
        
        sXML = bucs2
    End If
    
    Dim x As CXML
    Set x = NewCXML()
    Dim tXML As xml
    '解析XML文本到XML结构体
    ret = x.Decode(sXML, tXML)
    If VBA.Len(ret) Then
        MsgBox ret
        Exit Sub
    End If
    
    Dim arr() As String
    Cells.Clear
    arr = XML2Array(tXML)
    Range("A1").Resize(UBound(arr, 1) - LBound(arr, 1) + 1, UBound(arr, 2) - LBound(arr, 2) + 1).Value = arr  '不用-1因为0是root,正好作为标题
    
    Set x = Nothing
    Set zip = Nothing
End Sub
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 VBA 学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档