Linking drop-down selection to slicer - excel

I have a drop-down list (Excel data-validation) with the same options as a slicer (both from different sources).
How do I link my drop-down list selection to my slicer?
Nothing is recorded when I make a selection on a drop-down list.
E.g.
Drop-down list: Area 1, Area 2, Area 3
Slicer: Area 1, Area 2, Area 3
Goal: If I select Area 3 from my drop-down list, my slicer should have Area 3 selected too.

You need a event routine for Change that is triggered whenever the cell where the dropdown lives is changed, and a routine that changes the slicer.
Put the following code to the worksheet object in the VBA-Editor (not to a new module). Change the cell address (in the example it is E10 to the cell you are using). If you have more than one slicer in your workbook, you have to change the index to SlicerCaches to the one you want to modify (as usual in VBA, you can use the index number or the name).
Option Explicit
' The Event routine
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(False, False) = "E10" Then
SelectSlicerItem ThisWorkbook.SlicerCaches(1), Target.value
End If
End Sub
The following routine can be put either below the event routine or into a module. Note that if the itemText is not found in the slicer, all items will be selected.
Sub SelectSlicerItem(sc As SlicerCache, itemText As String, Optional defaultItem As String = "")
Dim si As SlicerItem, found As Boolean
found = False
sc.ClearManualFilter
For Each si In sc.SlicerItems
' Debug.Print si.Caption, si.value
If si.Caption <> itemText Then
si.Selected = False
found = True
End If
Next si
If Not found And defaultItem <> "" Then SelectSlicerItem sc, defaultItem
End Sub
Edit: Changed SelectSlicerItem to deal with default item.

Related

List Box Form Control selectrion triggers Worksheet SelectionChange

I am trying to keep track of changes (to be appeared in a chart) upon every changes made in the worksheet using this reference (codes are copied below as example reference).
The changes in the worksheet actually can be made by several List Boxes (form Control Menu) and other cells e.g. Input 3 and 4. Let's say the resulting value caused by any change appears in the cell G14, and as the example code I want to keep them in I14 (as in the example image).
The formula might be e.g. D14 + E14 + K14 + L14 where K14 and L14 are values linked to the ListBoxes.
Selections in Input 3 and 4 trigger Worksheet_Change but selections in List Box apparently don't, shall I add a macro for List Box callback in which Worksheet_Change gets triggered?
Apart from that, if there is any better saving the results method, please mention it.
Many thanks in advance!
Dim xVal As String
Private Sub Worksheet_Change(ByVal Target As Range)
Static xCount As Integer
Application.EnableEvents = False
If Target.Address = Range("G14").Address Then
Range("I14").Offset(xCount, 0).Value = xVal
xCount = xCount + 1
Else
If xVal <> Range("G14").Value Then
Range("I14").Offset(xCount, 0).Value = xVal
xCount = xCount + 1
End If
End If
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
xVal = Range("G14").Value
End Sub
As you are asking about trigger event to run a macro on selection of listbox value (form control), I believe this could be considered as answer. I am sure someone with better knowledge will improve it.
Worksheet_Change event occurs when a cell or range of cells is changed manually (not by any auto process like calculation or selection of listbox value)
There can be different scenarios
First
There is no link between calculation of cells affected by the listbox change. Say, in First ListBox, you select 10, and cell A2 is updated to 10 and cell A3 is calculated value changed to 30. Then You select in second listbox 15 and cell B2 is changed to 15 and cell B3 is calculated independently if A2 and A3 to 90.In this case these are independent listboxes and their results. So, in this case, you can assign macro to each listbox which will run every time you change value in each listbox.
Second
Dependent calculations: Say the desired result for tracking is in D3 which will be calculated only on selection of four listbox values in A2, B2, C2 and D2. In this case you will not like to run macro for every list change but only after selecting values in all listboxes and calculation of D3. So in that case, instead of assigning macros to all the listboxes you could assign it only to last listbox.
Third
By now you must have understood there are two events taking place. One is selection of listbox value and second is calculation. In the second scenario, if you want to run macro for every change in calculation, say when you select A2 and when you select B2, etc. then you can simply use calculation event instead of assigning macro to every listbox. It will run everytime when a value is changed causing worksheet to calculate.
For assigning macro to listbox (form control) --- You can directly assign a macro to the list box.. First create a macro in VBA . Then Just right click on the list box and click assign macro. then select a macro to be assigned. .. The macro will be run when you click the listbox to change the value
Also, as you want to track the result calculated with macro, you need the sheet to be calculated first. Start the macro with Worksheet.Calculate method to be safe (in case formula results are not updated for some reason).
Tahnks to #Naresh, solved the problem in the following way, any improvement editis more than welcome since I know the codes might seem inefficient!
Dim xVal As String
Public Function customRecorder(Target As String)
Static xCount As Integer
Application.EnableEvents = False
Range("I14").Offset(xCount, 0).Value = xVal
xCount = xCount + 1
Application.EnableEvents = True
End Function
Private Sub Worksheet_Calculate()
xVal = Range("G14").Value
customRecorder (Range("G14"))
End Sub

Spin Button for excel

I am trying to add a spin button to increment a value where ever the data is present.
I manually added a spin button for one field to increment the value. How can add spin buttons where ever a the value is present. Something like shopping cart.
Private Sub quantity_SpinDown()
Range("M6").Value = Range("M6") - 1
End Sub
Private Sub quantity_SpinUp()
Range("M6").Value = Range("M6") + 1
End Sub
I am expecting this spin button where ever there is an item in cart is present to increment the value of the item in the cart.Check Image here
You can create a macro to dynamically create spinners. In the example bellow you can select some cells in your worksheet and then execute the following Sub:
Option Explicit
Sub createSpinnersInSelection()
Dim spinner As OLEObject
Dim selectedCell As Range
For Each selectedCell In Selection
' Creates a spinner
Set spinner = selectedCell.Parent.OLEObjects.Add(ClassType:="Forms.SpinButton.1", Top:=selectedCell.Top, Left:=selectedCell.Left, Height:=selectedCell.RowHeight, Width:=15)
' Setting spinner properties
With spinner
' Cell to change the value
.LinkedCell = selectedCell.Address(0, 0)
With .Object
' Initial value
.Value = 0
' Increment of cell
.SmallChange = 1
End With
End With
Next selectedCell
End Sub
You may add more properties such as spinner color and others (the code was adapted from this thread)
Important note: You may need to tweak a little bit the .LinkedCell value since when you filter the columns it may keep the original cell reference, changed the value in a different cell than the expected one.

Linking Excel ComboBox with List Based on Independent Cell

I'm attempting to add items to an Excel Combobox, based on the value of an independent cell. So what I need is an IF statement, obviously.
So it should look something like this, (note: C1 is the independent cell):
IF C1 = "3"
AddItem "One"
AddItem "Two"
ELSE IF C1 = "4"
AddItem "Three"
.etc.
The problem is that I don't know how to properly link the ComboBox such that it knows when the independent cell value has changed to trigger a clearing of existing items in the ComboBox and repopulation of new items.
This code needs to go on the sheet with your target cell C1
Every time your cell C1 is changed, it will force the code you insert to execute. In this case, it will force an update to your dropdown list.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("C1"), Range(Target.Address)) Is Nothing Then
Application.EnableEvents = False
'YOUR CODE HERE
Application.EnableEvents = True
End If
End Sub
Edit 1: (How to add items to a combo box?)
Add an ActiveX Control Combo Box
Developer Tab > Insert > ActiveX Controls > ComboBox
You can then refer to your Combo box inside your loop as follows:
Combobox1.Clear 'To clear
ComboBox1.AddItem "Text" 'To Add

Set cell vlookup value based on changing Combobox value

I have input a combobox in an Excel sheet. I want it to work so that the user who does not have access to the VBA can select a value from the dropdown and then the value in another cell will perform a vlookup on this value.
In the first instance I have inserted a box and am trying to set a cell value based on this.
Sub InsertComboBox()
#inserts dropdown box on the front page and sets the values as the list of DMA from the pipe_totals sheet
#this should be the most complete list so will not change dependant on asset
Dim arearange As Range
Set arearange = Sheets("pipe_totals").Range("a:a")
lastrowi = Application.WorksheetFunction.CountA(arearange)
Sheets("front page").Activate
With Range("f5:g5")
Set Combo = ActiveSheet.DropDowns.Add(.Left, .Top, .Width, .Height)
End With
Combo.List() = Sheets("pipe_totals").Range("A2:A" & lastrowi).Value
.Range("k9").Value = Combo.Value 'only works on current combobox value which is 0
End Sub
Is there a way I can set this so the vlookup is dynamic depending on the users selection?
In this example, just set the right combo name. It should be ok, provided that your combobox lists values from "Range("A2:A" & lastrowi)" as you mention above.
Sub "comboname"_Change()
Dim list_val As Long
list_val = Worksheets("front page").Shapes("comboname").ControlFormat.Value
Range("K9") = Worksheets("pipe_totals").Cells((list_val + 1), 1)
End Sub
Sub test()
Dim z As Shape
For Each z In Worksheets("front page").Shapes
Debug.Print z.Name
Next z
End Sub
As far as I understand, you want that everytime the combobox value changes, cell K9 will have the same value also. Is that right? If this the case, then right click on the combobox and select "Assign Macro". Then select "Create". Then inside the sub created, which should look like this:
Sub "comboname"_Change()
End Sub
You should also paste the final code line.
.Range("k9").Value = Combo.Value
Doing so, means you want that line of code executed every time the combobox value changes.

VBA multiple checkbox userform to single cell

I am using a userform with multiple checkboxes in it. My goal is to have all checkboxes return their values (unique two letter acronyms) to a single cell. I am not sure how to accomplish this. I have no VBA experience prior to today.
You can record a macro to get your other relevant code for VBA but this should help:
Range("A" & LastRow).Value = CheckBox1.Value & CheckBox2.Value & CheckBox3.Value 'etc.
'Concatenate CheckBox values with "&" (the values will be True or False though)
Set linkcell of each checkbox to a different cell -.e.g. checkbox1 to cell A1, checkbox2 to cell A2, etc
For each link cell, use If formula in its adjacent cell to test the link cell's content and return a string or a blank,
e.g. if(A1=True,"AA","") in cell B1, if(A2=True,"BB","") in cell B2, etc
Finally, concatenate results of 'if' Formulas in another cell: e.g. B1&","&B2&","&B3, using comma as separaters
To do this, you can make a collection of all of the Checkboxes in the form. Heres my code:
Private mcolCHK As Collection 'This creates a modular level collection, which will keep track of all of the checkboxes
Private Sub cmdOK_Click()
Dim objA As Object, strResults As String, i As Integer
i = 1
For Each objA In mcolCHK
strResults = strResults & i & Left(objA.Value, 1)
i = 1 + i
Next
Unload frmTestForm 'rename this the name of your form
MsgBox strResults
'instead of using a message box, you can say "strResults = Sheets(sheet1).range("A1").value
'This part may be customized as needed
End Sub
Private Sub UserForm_Initialize()
Set mcolCHK = New Collection
mcolCHK.Add chkAtt1 'you will have to add one of these for each checkbox (simply replace "chkAtt1" with the name of your first checkbox
mcolCHK.Add chkAtt2 'and repeat for each checkbox
End Sub
Checkboxes always give a value of True or False. with this method, you will get the number of the checkbox (in order of how you added them to the collection in the UserForm_Initialize() sub) and the first letter of the result (T or F). When i ran this, I had two checkboxes, and checked each one when the form ran. This gave me a result of "1T2T". This can be changed as needed. All you really need is how this all works. just make sure to change all the names to match the names of the variables you used.

Resources