Spin Button for excel - 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.

Related

How to remove item from combobox in a userform?

I have a list of names in a sheet. I set these names as my RowSource for a combobox on a useform.
There are two Comboboxes involved. One starts full, the other starts empty.
I want when I click on a name from the first (full) combobox, said name to be added to the other combobox, and removed from the original combobox (and vice versa eventually).
I can't remove anything with RemoveItem.
I went the 'Menu.ListeAjoutAg.ListIndex' way to get my current selection's index ('Menu' is the UserForm and 'ListeAjoutAg' is the combobox), but it did not work.
Tried inputting through a variable I created real quick, 'b', but same result. No index number works. I checked and I only feed the function integers (0, 1, 3, 4...) that are correct and/or well within the scope of my list (about 45 names).
Private Sub ListeAjoutAg_Change()
a = Menu.ListeAjoutAg.Text
b = Menu.ListeAjoutAg.ListIndex
Menu.ListeRetirer.AddItem (a) ' goes fine till there
Menu.ListeAjoutAg.RemoveItem (b) 'and here it goes wrong
Menu.ListeRetirer.Enabled = True
Menu.ListeRetirer.Visible = True
End Sub
As already mentioned: You can't add or remove items from a Listbox if you have set the Rowsource property.
However, it is rather easy to fill a Listbox from a range - simply copy the cell values into an array and assign the array as List. See for example VBA Excel Populate ListBox with multiple columns
Put the following routine into your form and call it from the form Activate event.
Private Sub fillListBox(r As Range)
Me.ListeAjoutAg.Clear
Me.ListeAjoutAg.ColumnCount = r.Columns.Count
Dim data
data = r.Value
Me.ListeAjoutAg.List = data
End Sub
Private Sub UserForm_Activate()
Dim r As Range
' Replace this with the range where your data is stored.
Set r = ThisWorkbook.Sheets(1).Range("A2:C10")
fillListBox r
End Sub

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

How to correctly initialize and extract Listbox Value - Userform VBA

I have a Userform in which I want the user to select a word in each of two listbox and then save them in a sheet. The user can also (in theory) leave the pre-selected word. Here's the code I have written :
Private Sub UserForm_Activate ()
With ListBox1 'This list is about the stake
.AddItem "Essential"
.AddItem "Important"
.AddItem "Not interesting"
End With
'then I try to initialize the value of the stake.
ListBox1.Value = "Important"
With ListBox2 'This is a second list, about priority
.AddItem "Auto"
.AddItem "Yes"
.AddItem "No"
End With
'then I try to initialize the value of the priority
Listbox2.Value="Yes"
End Sub ()
But my problem is that, even though the two list seem to have been initialize correctly (correct word highlighted in the list when I run the UserForm), I can't extract the value of one of the list. When I run the following code :
Private Sub CommandButton2_Click()
Feuil1.Cells(1,1)=Listbox1.Value
Feuil1.Cells(1,2)=Listbox2.Value
End sub ()
Excel is able to extract the value of Listbox2 (Priority) : "Yes" but not the value of Listbox1 (Stake) : "Important". And I don't get why the code would work for one but not the other!
One more element : if I manually select a word in the list, then Excel is able to give me the value of both listbox.
Any clue?
How to get the current value of a ListBox
Seems that the .Value property recognizes the correct list row, but doesn't react to the second listbox unless it gets focus or is activated manually.
So a brute (and not recommendable) work around would be to set focus each time you have to get the current value of the 2nd listbox, too.
(This seems to be nerve-racking btw and ressembles to a certain extent to permanently selecting or activating cells instead of recommended direct referencing fully qualified ranges.)
'...
Me.ListBox2.SetFocus
Feuil1.Cells(1, 2) = Me.ListBox2.Value
You are on the sure side, however using the listboxes' .List property.
.ListIndex as first argument indicates the current "row" by a zero-based index (0 equals row 1, 1 the 2nd one row, etc.);
the 2nd argument 0 indicates the row index (i.e. column 1; btw the only one here).
Private Sub CommandButton2_Click()
Feuil1.Range("A1:B1") = vbNullString
With Me.ListBox1
If .Listindex >-1 then Feuil1.Cells(1, 1) = .List(.ListIndex, 0)
End With
With Me.ListBox2
If .Listindex >-1 then Feuil1.Cells(1, 2) = .List(.ListIndex, 0)
End With
Try this, it works well for me.
Private Sub CommandButton2_Click()
Feuil1.Cells(1,1)=Listbox1.Value
Feuil1.Cells(1,2)=Listbox2.Value
Unload Me
End sub

Linking drop-down selection to slicer

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.

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.

Resources