How to add a custom Ribbon tab using VBA?

后端 未结 7 729
深忆病人
深忆病人 2020-11-22 14:47

I am looking for a way to add a custom tab in the Excel ribbon which would carry a few buttons. I chanced on some resources addressing it via Google but all look dodgy and o

7条回答
  •  春和景丽
    2020-11-22 15:23

    I was able to accomplish this with VBA in Excel 2013. No special editors needed. All you need is the Visual Basic code editor which can be accessed on the Developer tab. The Developer tab is not visible by default so it needs to be enabled in File>Options>Customize Ribbon. On the Developer tab, click the Visual Basic button. The code editor will launch. Right click in the Project Explorer pane on the left. Click the insert menu and choose module. Add both subs below to the new module.

    Sub LoadCustRibbon()
    
    Dim hFile As Long
    Dim path As String, fileName As String, ribbonXML As String, user As String
    
    hFile = FreeFile
    user = Environ("Username")
    path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
    fileName = "Excel.officeUI"
    
    ribbonXML = "" & vbNewLine
    ribbonXML = ribbonXML + "  " & vbNewLine
    ribbonXML = ribbonXML + "    " & vbNewLine
    ribbonXML = ribbonXML + "    " & vbNewLine
    ribbonXML = ribbonXML + "      " & vbNewLine
    ribbonXML = ribbonXML + "        " & vbNewLine
    ribbonXML = ribbonXML + "          " & vbNewLine
    ribbonXML = ribbonXML + "        " & vbNewLine
    ribbonXML = ribbonXML + "      " & vbNewLine
    ribbonXML = ribbonXML + "    " & vbNewLine
    ribbonXML = ribbonXML + "  " & vbNewLine
    ribbonXML = ribbonXML + ""
    
    ribbonXML = Replace(ribbonXML, """", "")
    
    Open path & fileName For Output Access Write As hFile
    Print #hFile, ribbonXML
    Close hFile
    
    End Sub
    
    Sub ClearCustRibbon()
    
    Dim hFile As Long
    Dim path As String, fileName As String, ribbonXML As String, user As String
    
    hFile = FreeFile
    user = Environ("Username")
    path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
    fileName = "Excel.officeUI"
    
    ribbonXML = "" & _
    ""
    
    Open path & fileName For Output Access Write As hFile
    Print #hFile, ribbonXML
    Close hFile
    
    End Sub
    

    Call LoadCustRibbon sub in the Wookbook open even and call the ClearCustRibbon sub in the Before_Close Event of the ThisWorkbook code file.

提交回复
热议问题