Accessing the Ribbon from Other Classes in your Project
The Beta 1 release of Visual Studio Code Name Orcas Tools for the Microsoft Office System introduced a new visual design canvas called the Ribbon Designer.
You can use the Ribbon Designer to add custom tabs, groups, and controls to the Ribbon of a 2007 Microsoft Office system application.
Accessing controls on the Ribbon at run time is fairly easy as long as you are writing your code in the Ribbon class. For example, to change the label of a button on the Ribbon, you could type the following:
[Visual Basic]
Me.Button1.Label = "Hello World"
[C#]
this.button1.Label = "Hello World";
However, if you want to do this from anywhere else in the project, it can prove to be a bit more challenging.
To do this, use the GetRibbonObjects() method of the ThisAddin, ThisWorkbook, or ThisDocument class to return an object that represents the Ribbon in your project. You can then access controls on the Ribbon.
The following example sets the label of a button on the Ribbon of an Excel Workbook customization project.
[Visual Basic]
Private Sub Sheet1_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
Dim ribbons As Microsoft.VisualStudio.OfficeTools.Ribbon.ComponentModel.Ribbon() = Globals.ThisWorkbook.GetRibbonObjects()
Dim ribbon As Ribbon1 = CType(ribbons(0), ExcelWorkbook3.Ribbon1)
ribbon.Button1.Label = "Hello World"
End Sub
[C#]
private void Sheet1_Startup(object sender, System.EventArgs e)
{
Microsoft.VisualStudio.OfficeTools.Ribbon.ComponentModel.Ribbon[] ribbons = Globals.ThisWorkbook.GetRibbonObjects();
Ribbon1 ribbon = (ExcelWorkbook2.Ribbon1)ribbons[0];
ribbon.button1.Label = "Hello World";
}
If you are using a C# project, you need to change the Modifiers property of each Ribbon control that you want to access to either Public or Internal. To do this, perform the following steps:
1. On the Ribbon Designer, select a control that you want to make available to your code.
2. On the View menu in Visual Studio, click Properties Window.
3. In the Properties window, click the field next to the Modifiers property, and select Public or Internal from the drop-down list.
Note: This behavior will change for Beta 2 and beyond.
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm.