Você está na página 1de 8

Criao de menus pop-up em todas as

verses do Excel
http://msdn.microsoft.com/en-us/library/office/gg987030(v=office.14).aspx
Office 2010

54 out of 69 rated this helpful - Rate this topic


Summary: See how to create popup menus that work in all versions of Microsoft Excel.
Last modified: April 04, 2011
Applies to: Excel | Excel 2010 | Office 2007 | Office 2010 | SharePoint Server 2010 | VBA
Published: April 2011
Provided by: Ron de Bruin, Excel MVP | Frank Rice, Microsoft Corporation
Contents

Introduction to Popup Menus

Creating Popup Menus

Displaying the Popup Menu

Conclusion

Additional Resources

Introduction to Popup Menus


Um menu pop-up (tambm chamado s vezes contextual ou menus de atalho) um menu em
uma interface de usurio (UI) que aparece de alguma ao do usurio, como um clique direito
do mouse. Um menu pop-up oferece um conjunto limitado de opes que esto disponveis no
atual Estado, ou contexto, da aplicao. Menus de contexto pode ser constitudo por uma srie
de comandos individuais, uma lista de comandos aninhados, ou geralmente como uma
combinao de ambos. Menus pop-up esto disponveis em todos os programas do Microsoft
Office. Como menus pop-up so criados varia dependendo da verso do programa Microsoft
Office, como o Microsoft Excel, Microsoft Outlook e Microsoft Word.
Mais recentemente, a tcnica para criar menus que funcionam em diferentes verses do
Microsoft Office diferente, principalmente porque no sistema Microsoft Office 2007, a
Microsoft substituiu a estrutura do menu Command Bar com a UI fita. Assim, em Microsoft
Office Excel 2007, por exemplo, o comando barra de menu planilha visto em verses
anteriores do Excel foi substitudo com comandos semelhantes sobre a interface do usurio
fita. Esta diferena na interface do usurio significa que, para os desenvolvedores, criando uma
estrutura de menu que funciona em todas as verses do Microsoft Office mais desafiador.
No entanto, como voc ver neste artigo, uma tcnica que funciona envolve o uso de um
menu pop-up Command Bar.
Creating Popup Menus
In this section, you create a popup menu in Excel. Note that one way that built-in or custom
context menus differ from popup menus is that context menus are only displayed when you
right-click the mouse. Popup menus on the other hand can be displayed when you want
them to be.

To create a popup menu in Excel


1. Abra um novo livro.
2. Salve o arquivo usando qualquer um .xls ou .xlsm (arquivo habilitado para macro no Excel
2007 e Excel 2010) arquivo extenso de nome de acordo com a verso do Excel que voc est
usando.
3. Pressione Alt + F11 para abrir o Editor do Visual Basic.
4. No menu Inserir, clique em mdulo para criar um mdulo para conter seu cdigo.
5. Digite ou cole o seguinte cdigo no Mdulo1.
VB
Option Explicit
Public Const Mname As String = "MyPopUpMenu"
Sub DeletePopUpMenu()
' Delete the popup menu if it already exists.
On Error Resume Next
Application.CommandBars(Mname).Delete
On Error GoTo 0
End Sub
Sub CreateDisplayPopUpMenu()
' Delete any existing popup menu.
Call DeletePopUpMenu
' Create the popup menu.
Call Custom_PopUpMenu_1
' Display the popup menu.
On Error Resume Next
Application.CommandBars(Mname).ShowPopup
On Error GoTo 0
End Sub
Sub Custom_PopUpMenu_1()
Dim MenuItem As CommandBarPopup
' Add the popup menu.
With Application.CommandBars.Add(Name:=Mname,
Position:=msoBarPopup, _
MenuBar:=False, Temporary:=True)
' First, add two buttons to the menu.
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 1"
.FaceId = 71
.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"
End With
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 2"
.FaceId = 72
.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"

End With
' Next, add a menu that contains two buttons.
Set MenuItem = .Controls.Add(Type:=msoControlPopup)
With MenuItem
.Caption = "My Special Menu"
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 1 in menu"
.FaceId = 71
.OnAction = "'" & ThisWorkbook.Name & "'!" &
"TestMacro"
End With
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 2 in menu"
.FaceId = 72
.OnAction = "'" & ThisWorkbook.Name & "'!" &
"TestMacro"
End With
End With
' Finally, add a single button.
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 3"
.FaceId = 73
.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"
End With
End With
End Sub
Sub TestMacro()
MsgBox "Hi there! Greetings from the Netherlands."
End Sub

1. Press Alt+Q to close the Visual Basic Editor.


2. Save the file.

Note

Voc pode alterar as imagens dos botes, alterando os valores FaceID. Encontre mais
informaes sobre o website do Atron.
Apresentar o menu de Popup
Nesta seo, voc adiciona o cdigo para o projeto para demonstrar os diferentes
mtodos para mostrar o menu de contexto.
Usar um atalho para exibir o menu pop-up
1. Pressione Alt + F8 para abrir a caixa de dilogo macro.
2. Selecione a macro CreateDisplayPopUpMenu.
3. Clique no boto Opes na caixa de dilogo.
4. Digite a letra m, e clique em OK.

5. Feche a caixa de dilogo e tentar o atalho Ctrl m. Voc v o menu mostrado na


Figura 1.
Figura 1. O menu personalizado exibido

1. A caixa de dilogo mostrada na Figura 2 Clique no boto 1. exibida.


Figura 2. caixa de dilogo exibida a partir do menu pop-up

1. Salve o arquivo.

Ateno

possvel que, se voc tem um outro aberto pasta de trabalho que usa o mesmo atalho
como aquele que voc usa aqui, voc no pode ver o menu pop-up quando voc usa o
atalho.
Voc pode fechar a pasta de trabalho sem excluir o menu. Este no um problema porque
quando o menu foi criado usando o With Application.CommandBars.Add mtodo, seu
parmetro Temporary definido como True. Isso exclui automaticamente o menu quando
voc fechar o Excel. No entanto, sempre uma boa prtica para excluir explicitamente o
menu usando o seguinte procedimento.To delete the menu
1. Press Alt+F11 to open the Visual Basic Editor.
2. Open the ThisWorkbook module.
3. Paste this code into the module.
VB

Private Sub Workbook_Deactivate()


Call DeletePopUpMenu
End Sub

4. Press Alt+Q to close the Visual Basic Editor.


5. Save the file.
6. Na seo seguinte, voc adiciona o cdigo para o projeto que usa eventos de pasta de
trabalho para adicionar um boto para o menu Cellcontext que chama o menu de
contexto. O menu de contexto celular o que voc v quando voc clica com o boto
direito em uma clula ou seleo de uma clula.

Note

Tambm possvel adicionar todos os seus itens de menu a um menu de contexto. Para
saber mais, consulte Customizing Context Menus in All Versions of Microsoft
Excel.
To add a button to the Cell context menu
1. Press Alt+F11 to open the Visual Basic Editor.
2. In Module1, cole o seguinte cdigo abaixo do cdigo existente.
VB

Sub AddToCellMenu()
Dim ContextMenu As CommandBar
' First, delete the control to avoid duplicates.
Call DeleteFromCellMenu
' Set Context Menu variable to point to the Cell menu.
Set ContextMenu = Application.CommandBars("Cell")
' Add one custom button to the Cell menu.
With ContextMenu.Controls.Add(Type:=msoControlButton, before:=1)
.OnAction = "'" & ThisWorkbook.Name & "'!" &
"CreateDisplayPopUpMenu"
.FaceId = 59
.Caption = "My Popup menu"
.Tag = "My_Cell_Control_Tag"
End With
End Sub
Sub DeleteFromCellMenu()
Dim ContextMenu As CommandBar
Dim ctrl As CommandBarControl
' Set ContextMenu variable to point to the Cell menu.
Set ContextMenu = Application.CommandBars("Cell")
' Delete custom controls with the tag: My_Cell_Control_Tag.
For Each ctrl In ContextMenu.Controls
If ctrl.Tag = "My_Cell_Control_Tag" Then
ctrl.Delete
End If
Next ctrl
End Sub

3. Open the ThisWorkbook module.

4. Digite ou cole o seguinte cdigo no mdulo. Substitua o evento Desactivar do exemplo


anterior com o seguinte, se ele existir.
VB

Private Sub Workbook_Activate()


Call AddToCellMenu
End Sub
Private Sub Workbook_Deactivate()
Call DeleteFromCellMenu
Call DeletePopUpMenu
End Sub

5. Press Alt+Q to return to the Excel window.


6. Save the file, close, and then reopen it.
7. Right-click any cell. You see the Cell context menu as shown in Figure 3.
Figure 3. Customized Cell context menu

8. Click the top menu item to see the dialog box displayed as shown in Figure 2.
You may want to display a different menu for each sheet or only display the menu on a few
sheets. You use the following procedures to do that.

To limit the scope of a Popup menu


1. In the same workbook, press Alt F11 to open the Visual Basic Editor.
2. In Module1, type or paste the following macro below the existing code.
VB

Sub Custom_PopUpMenu_2()
' Add popup menu with three buttons.
With Application.CommandBars.Add(Name:=Mname,
Position:=msoBarPopup, _
MenuBar:=False, Temporary:=True)
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 1"
.FaceId = 71
.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"
End With
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 2"
.FaceId = 72

.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"


End With
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 3"
.FaceId = 73
.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"
End With
End With
End Sub

3. Next, still in Module1, replace the macro named CreateDisplayPopUpMenu with the
following macro.
VB

Sub CreateDisplayPopUpMenu()
' Delete the popup menu if it exist.
Call DeletePopUpMenu
' Create the correct menu based on the active worksheet.
Select Case ActiveSheet.Name
Case "Sheet1": Call Custom_PopUpMenu_1
Case "Sheet2": Call Custom_PopUpMenu_2
Case Else: MsgBox "Sorry no Popup Menu"
End Select
' Show the popup menu.
On Error Resume Next
Application.CommandBars(Mname).ShowPopup
On Error GoTo 0
End Sub

4. Press Alt+Q to return to the Excel window and save the file.
5. Now, try it out by pressing Ctrl m first in Sheet 1, then in Sheet2, and finally in Sheet3. Note
that you may need to re-create the keyboard shortcut combination (Ctrl m) by using the
procedures that are described at the beginning of this article. You can also test this out by
right-clicking a cell and then using the Cell menu in Sheet1, then in Sheet2, and finally in
Sheet3.
When Sheet1 is active, the popup menu with 3 buttons and another menu with 2 buttons
will be displayed. And when Sheet2 is active, the popup menu with 3 buttons will be
displayed. If any other worksheet is active, theSorry no Popup Menu dialog box appears.
This gives you full control of the popup menu options available on each worksheet.
In the following steps, you add a button to the Quick Access Toolbar in Excel 2007 and
Excel 2010 that displays a popup menu.
1.
2.
3.
4.

To add a menu button to the Quick Access Toolbar


Open the workbook from the previous examples and make sure that you save it with
the .xlsm (macro-enabled file) file name extension.
Right click on the Quick Access Toolbar and select Customize Quick Access Toolbar.
In the Choose commands from drop-down list, select Macros.
In the Customize Quick Access Toolbar drop-down list, select For
<yourworkbookname>.xlsm.

5. Select the CreateDisplayPopUpMenu macro, click Add, and then click OK. This displays
the button shown in Figure 4 on the Quick Access Toolbar. You can use Modify in the
customize Quick Access Toolbar window to change the icon, if you want.
Figure 4. New button added to the Quick Access Toolbar

6. Finally, click OK and save the file.


7. Click the button on the Quick Access Toolbar to display the menu.

Note

You only have to do this one time because the button is saved with the workbook. If you
send the file to other users, they can use your button on the Quick Access Toolbar.
Conclusion
Popup menus give you more flexibility in the options that you can offer to your users than
built-in or custom context menus. Popup menus can be attached to events, to existing
menus, or to the Quick Access Toolbar. You should continue to experiment with the
methods discussed in this article to see how you can add versatility in your own application.
Additional Resources
Find more information about the topics discussed in this article at the following locations:

Você também pode gostar