How to trigger a macro with change of ribbon tab? - excel

I have an Excel Workbook with a couple of custom ribbon tabs. I would like to activate a specified Sheet when clicking of particular custom ribbon tab.
Details:
The Workbook composed of a 5 Sheets has following additional ribbon tabs: "Parameters" and "Data Analysis". Each Tab has a few groups of controls. I need to add a trigger (macro?), which would automatically change a Sheet to Sheet3 (to run ActiveWorkbook.Sheets("Sheet3").Activate) only when a user picks the "Data Analysis" Tab.
I would appreciate any help.

It is possible to use a getVisible callback from a ribbon to achieve what you are looking for.
Here is an example xml for a tab (it should be nested inCustomUI and ribbon tags)
<tabs>
<tab id="ExampleTab" label="Example Tab">
<group id="ExampleGroup"
label="Example Group"
getVisible="GetVisibility"
tag="1"
>
</group>
</tab>
</tabs>
When someone clicks on the tab this xml will call GetVisibility sub in the workbook it belongs to. You can use tag property to pass a variable to the `Sub'. For example every tab can have its own tag, or it can be used for something else.
Now here is an example code for GetVisibility:
Public Sub GetVisibility(Control As IRibbonControl, ByRef Visible)
'your code to activate the worksheet can go here
Visible = True 'if you want to make a control visible
Select Case Control.Tag 'you can use Control.Tag to get a variable from ribbon
Case "1"
Case Else
End Select
End Sub
The only issue is that this code will normally only be called the first time you click on a tab. To get the code to rerun I think you need to invalidate your ribbon control. For that you would have to store your ribbon in a global scope variable at initialization. The last time I checked you may need a workaround for that, such as storing ribbon address in a worksheet. There is a number of question on Stack about that, for example: this one.

Related

Excel hiding columns [duplicate]

Is there a way, to trigger an event (call a sub) in Excel VBA, when i manually hide a row/column?
I want the same row to be hidden in all following sheets, when it is hidden in a particular sheet.
Is that possible?
Thanks in advance
There is no direct event trigger to capture hiding or unhiding columns. There are clumsy workarounds, using formulae in cells but those feel like a kludge when using and not really flexible.
However, there is an indirect way to capture this event if you use Excel 2007 or newer. This is neat and extremely flexible.
Modify the Ribbon XML (if it's present): You need to be able to modify the Ribbon's customUI14.xml (for Excel 2010) or customUI.xml (for Excel 2007).
Create the custom Ribbon UI XML file (if not present): You may use Ron De Bruin's excellent Custom UI Editor from http://www.rondebruin.nl/win/s2/win001.htm (which is also endorsed in quite a few official Microsoft examples).
XML changes for capturing events: Open the Excel file in the Custom UI Editor and add the XML code as shown below. That will enable a column hide or unhide event to trigger a macro in your code.
VBA code to execute your actions: Add the code listed below to take action once the event is captured.
Reference: This excellent solution was provided by Andy Pope here (MSDN link).
Custom XML code:
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" >
<commands >
<command
idMso="ColumnsHide"
onAction="Column_Hide_Macro"/>
<command
idMso="ColumnsUnhide"
onAction="Column_UnHide_Macro"/>
</commands >
</customUI>
Custom UI Editor screenshot:
VBA code:
Sub Column_Hide_Macro(control As IRibbonControl, ByRef CancelDefault)
MsgBox ("You have hidden a column")
' You may put your code here
' to check if your monitored row is hidden
CancelDefault = False ' This enables the default action to continue
End Sub
Sub Column_UnHide_Macro(control As IRibbonControl, ByRef CancelDefault)
MsgBox ("You have unhidden a column")
' You may put your code here
' to check if your monitored row is unhidden
CancelDefault = False ' This enables the default action to continue
End Sub

I want to create an add button

I am newbie in excel and I really need a button that if pressed adds a certain value to the cells I selected, is that possible?
You can add buttons to Excel by enabling developer mode:
On the File tab, go to Options > Customize Ribbon.
Under Customize the Ribbon and under Main Tabs, select the Developer check box.
Then on the developer ribbon you can click insert, then select a button to draw onto the sheet.
You will then be given the option to assign a macro to the button (Also later accessible by right clicking the button).
As for the VBA code of the macro, you would need to be more specific about what functionality you require, is the 'certain value' to be added to the selected cells always the same value?
Someone answered me in two minutes on another site with this perfect code for what I wanted, thanks a lot sir. It works like magic.
Sub Add_to_Selection()
If Not IsNumeric([E4]) Then
Exit Sub
Else
Dim cell As Range
For Each cell In Selection
cell.Value = cell.Value + [E4].Value
Next cell
End If
End Sub

Stop macro to allow the workbook to be edited

I have written a code to open a workbook and filter data by the number in a particular column. I need to filter "0" first and then edit the data and then filter between "+8" and "-8".
I added a message box to pause the macro but I am not able to edit the opened workbook while the message box is displayed. I tried with "Application.waiting" option.
I need to pause the macro automatically and start it manually.
Sub Filter_data()
Workbooks.open"D:\Reposrts\AAA.csv"
Activesheet.Range("I1:I100").Autofilter field:=1,Criterial:="0"
Activesheet.columns("A:Z").Autofit
MsgBox"Task ok" 'Here I need to pause the macro and allow for edit opened wb and then manually start macro for below line'
Activesheet.Range("I1:I100").Autofilter field:=1,Criterial:=">8", Opersator:=xlAnd, Criterial:="<-8"
End Sub
Split your existing Macro into two parts
The first part contains everything up to have the MsgBox"Task ok" line
The second part contains everything after that point
Create a Modeless (or "Non-Modal") User Form with your label and an "OK" button to call the second part of your split macro
"Modeless" means you can edit the workbook while the User Form is open. MsgBox is "Modal", which is why you can't edit anything. More details available from Microsoft
Replace the MsgBox"Task ok" line in the first part of your split macro with a line that opens your User Form.
Once the first half-macro has finished, and the User Form is waiting for you to click "OK", you will be able to edit workbooks. Once you click "OK", the second part will start.
It is probably best to first consider if the "edits" you need the user to make are possible via VBA, a User Form, or a DialogBox (which include the likes of the "Select Range" DialogBox, or the "Colour Picker" DialogBox)
I would recommend you not to try to edit the Workbook while a macro is running- I don't even think that is possible at all. Furthermore, try not to refer to ranges by activating/selecting ranges.
Activesheet.Range("I1:I100").Autofilter 'Instead of this use the code below
With Workbooks("AAA.csv")
.Sheets("NAME").Range("I1:I100).Autofilter
'More code
End With
Like Chillin mentioned, you could assign hotkeys to your filter macros- split them in two. Other than that, you can use buttons to activate the macros.
To assign a keyboard shortcut to a macro:
Press ALT+F8 to open the macro dialog box. Select the macro, and click on Options. In the window that opens you can assign a keyboard shortcut to the macro you selected.

Differences between Excel's Form Controls & ActiveX Controls

Why are there 2 types of controls available in Excel? (2 buttons, 2 combo boxes, 2 check box, etc...)
What's the difference between Forms Controls and ActiveX Controls? Which one should I use?
Some code samples I find online work with my controls, but others do not. How come?
How do I work with each type, and how can I tell the difference?
There is [eternal] confusion surrounding the two types of controls available to Excel — exacerbated by the contrasting terminology used by different online sources.
This is only a general overview of the differences between Form Controls and ActiveX Controls (based on my old notes that helped me finally figure out the differences!) Visit the included links for more detailed information about each control including code and sample projects. ☺
(Adapted from my original post here — now closed)
Overview:
There are two types of controls: Form controls and ActiveX controls:
Both types of controls can be used on worksheets but only ActiveX controls can be used on userforms.
Form controls are part of the Shapes collection (just like Drawing Objects), and thus are referred to like:
ActiveX controls are basically part of the worksheet and are therefore referred to like:
Both types of controls can be created, modified and deleted from either the worksheet, or programmatically with VBA, however, the 2 types of controls have slightly varying syntax when using VBA to refer to them.
Some sites discuss also discuss a Data Form. This is nothing more than a userform made specifically for data entry/manipulation of data, so it would've made more sense to call them (the more familiar sounding) "Data Entry Userform".
Office documentation also occasionally refers to a worksheet as a form. While this is technically correct, don't let this confuse you. Think of the word "form" as being used in a general sense:
Two Types of Controls
Form Controls
ActiveX Controls
The two look, behave, and are controlled similarly, but not identically. (List here.)
For example, let's compare the two types of Combo Boxes. In some programming languages, comparable controls are referred to as a "drop-down menu" or "drop-down list". In Excel, we have a "Form Control Combo Box", and an "ActiveX Control Combo Box":
(Click image to enlarge.)
☆ "Default name" applies to controls created manually. Controls created programmatically do not have (or require) a default name and therefore should have one assigned immediately upon creation.
(Source: my answer)
Control Availability
This image below shows which common controls are generally available for use in Worksheets and User Forms.
Other factors may affect control availability.
Office.com : Why are form-related commands or controls on the ribbon disabled?
Office.com : Overview of forms, Form controls, and ActiveX controls on a worksheet
MSDN : Add Controls to a User Form
About ActiveX controls and related Security Concerns
An ActiveX control is an extension to the VBA Toolbox. You use ActiveX controls just as you would any of the standard built-in controls, such as the CheckBox control. When you add an ActiveX control to an application, it becomes part of the development and run-time environment and provides new functionality for your application.
An ActiveX control is implemented as an in-process server (typically a small object) that can be used in any OLE container. Note that the full functionality of an ActiveX control is available only when used within an OLE container designed to be aware of ActiveX controls.
This container type, called a control container or control object, can operate an ActiveX control by using the control’s properties and methods, and receives notifications from the ActiveX control in the form of events. The following figure demonstrates this interaction:
(Source: this and this)
See also:
Wikipedia: ActiveX
Symantec.com : Discussion of ActiveX Vulnerabilities
How-To Geek : What ActiveX Controls Are and Why They’re Dangerous
Option Buttons (Radio Buttons)
In Excel, the two types of radio buttons are actually called Option Buttons. To further confuse matters:
the default name for the form control is OptionButton1.
the default name for the ActiveX control is Option Button 1.
A good way to distinguish them is by opening the control's Properties list (on the ribbon under the Development tab, or by right-clicking the control and choosing Properties, or hitting F4), because the ActiveX control has many more options that the simpler form control.
Option buttons and checkboxes can be bound together (so only one option at a time can be selected from the group) by placing them in a shared Group Box.
Select the group box control and then hold Ctrl while selecting each of the other controls that you want to group. Right-click the group box control and choose Grouping → Group.
The first two links below are separate sets of instructions for handling each type of option button.
HANDLING CONTROL EVENTS:
Form control events (Click event only)
Form control events are only able to respond to one event: the Click event. (More info here.) Note that this section doesn't apply to userforms since they use only ActiveX controls.
To add a procedure for the Click event:
Right-click the control and choose Assign Macro...
In the 'Assign Macro` Dialog:
Select an existing procedure, and click OK, or,
Create a new procedure in the VBE by clicking New..., or,
Record a new macro by clicking Record..., or,
to Remove the assigned event, delete its name from Macro Name field and click OK.
(Click image to enlarge.)
To rename, edit or delete existing macros, hit Alt+F8 to open the Macro interface:
ActiveX control events
ActiveX controls have a more extensive list of events to which they can be set up to respond.
To assign events to ActiveX controls, right-click the control and choose View Code. In the VBE, you can paste in code, or choose specific events from the drop-down list at the top-right of the VBE window.
(Click image to enlarge.)
Control event handling on a userform:
Events can also be used in controls on userforms. Since only ActiveX controls can be placed a userform, you'll have the "more coding + more functionality" trade-off.
ActiveX controls are added to userforms the same way as they are added to a worksheet. Keep in mind that any events assigned to the userform itself (ie., background) will be "blocked" in any areas covered up by a control, so you may need to assign the same events to the controls as well as the userform.
For example, in order to make this userform respond to MouseMove anywhere on the form, the same event code was applied to the userform, textboxes, option buttons and the frame:
VBA EXAMPLES
Add/Modify/Delete a form control option button using VBA:
Sub formControl_add()
'create form control
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.Shapes.AddFormControl(xlOptionButton, 25, 25, 100, 100)
.Name = "cOptionButton1" 'name control immediately (so we can find it later)
End With
End Sub
Sub formControl_modify()
'modify form control's properties
Dim ws As Worksheet: Set ws = ActiveSheet
ws.Shapes("cOptionButton1").Select
With Selection 'shapes must be Selected before changing
.Characters.Text = "wxyzabcd"
End With
End Sub
Sub formControl_delete()
'delete form control
Dim ws As Worksheet: Set ws = ActiveSheet
ws.Shapes("cOptionButton1").Delete
End Sub
Shapes.AddShape Method (Excel)
Shape Properties (Excel)
Characters Object (Excel)
Add/Modify/Delete an ActiveX command button using VBA:
Sub activexControl_add()
'create ActiveX control
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.OLEObjects.Add("Forms.CommandButton.1")
.Left = 25
.Top = 25
.Width = 75
.Height = 75
.Name = "xCommandButton1" 'name control immediately (so we can find it later)
End With
End Sub
Sub activexControl_modify()
' modify activeX control's properties
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.OLEObjects("xCommandButton1").Object
.Caption = "abcxyz"
.BackColor = vbGreen
End With
End Sub
Sub activexControl_delete()
' delete activeX control
Dim ws As Worksheet: Set ws = ActiveSheet
ws.OLEObjects("xCommandButton1").Delete
End Sub
OLEObjects.Add Method (Excel)
BackColor, ForeColor Properties (ActiveX Controls)
Add/Remove items from a form control combo box:
Sub ComboBox_addRemoveItems_FormControl()
Dim ws As Worksheet: Set ws = ActiveSheet
'add item to form control combo box
ActiveWorkbook.Sheets("Sheet1").Shapes("Drop Down 1").ControlFormat.AddItem "abcd"
'remove all items from from form control combo bo
ActiveWorkbook.Sheets("Sheet1").Shapes("Drop Down 1").ControlFormat.RemoveAllItems
End Sub
Add/Remove items from an ActiveX combo box:
Sub ComboBox_addRemoveItems_ActiveXControl()
Dim ws As Worksheet: Set ws = ActiveSheet
'add items to ActiveX combo box
ActiveWorkbook.Sheets("Sheet1").ComboBox1.AddItem "abcd"
'remove all items from ActiveX combo box
ActiveWorkbook.Sheets("Sheet1").ComboBox1.Clear
End Sub
More Information:
Office.com : Add a checkbox or option button (Form controls)
Office.com : Add a checkbox, option button, or toggle button (ActiveX controls)
Office.com : Overview of forms, Form controls, and ActiveX controls on a worksheet
Office.com : Enable selection through choice controls (check and list boxes)
Office.com : Add, edit, find, and delete rows by using a data form
MSDN : VBA Shape Members
MSDN : Using ActiveX Controls on Sheets (Office)
Exceldemy : How to Use Form Controls in Excel
MSDN : Using Windows Forms Controls on Excel Worksheets (Visual Studio)
Microsoft TechNet : Behaviour of ActiveX controls embedded in Office documents
Stack Overflow : What is the difference between “Form Controls” and “ActiveX Control” in Excel 2010?

Trigger Event in Excel VBA when Row or Column is hidden

Is there a way, to trigger an event (call a sub) in Excel VBA, when i manually hide a row/column?
I want the same row to be hidden in all following sheets, when it is hidden in a particular sheet.
Is that possible?
Thanks in advance
There is no direct event trigger to capture hiding or unhiding columns. There are clumsy workarounds, using formulae in cells but those feel like a kludge when using and not really flexible.
However, there is an indirect way to capture this event if you use Excel 2007 or newer. This is neat and extremely flexible.
Modify the Ribbon XML (if it's present): You need to be able to modify the Ribbon's customUI14.xml (for Excel 2010) or customUI.xml (for Excel 2007).
Create the custom Ribbon UI XML file (if not present): You may use Ron De Bruin's excellent Custom UI Editor from http://www.rondebruin.nl/win/s2/win001.htm (which is also endorsed in quite a few official Microsoft examples).
XML changes for capturing events: Open the Excel file in the Custom UI Editor and add the XML code as shown below. That will enable a column hide or unhide event to trigger a macro in your code.
VBA code to execute your actions: Add the code listed below to take action once the event is captured.
Reference: This excellent solution was provided by Andy Pope here (MSDN link).
Custom XML code:
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" >
<commands >
<command
idMso="ColumnsHide"
onAction="Column_Hide_Macro"/>
<command
idMso="ColumnsUnhide"
onAction="Column_UnHide_Macro"/>
</commands >
</customUI>
Custom UI Editor screenshot:
VBA code:
Sub Column_Hide_Macro(control As IRibbonControl, ByRef CancelDefault)
MsgBox ("You have hidden a column")
' You may put your code here
' to check if your monitored row is hidden
CancelDefault = False ' This enables the default action to continue
End Sub
Sub Column_UnHide_Macro(control As IRibbonControl, ByRef CancelDefault)
MsgBox ("You have unhidden a column")
' You may put your code here
' to check if your monitored row is unhidden
CancelDefault = False ' This enables the default action to continue
End Sub

Resources