Adding a tooltip to a ComboBox in Excel with VBA - excel

I've added two Dropdown (aka ComboBox) to a Sheet
Using this piece of code I can access the Dropdown but how can I add a tooltip on the Dropdown?
The best solution would be to show a different text for every item but if there is only an unique tooltip for the whole dropdown I can change it after selecting every item.
Sub DropDown1_Change()
Dim s As Object
Set s = ActiveSheet.Shapes(Application.Caller)
s.ToolTip = "Example"
Debug.Print s.ControlFormat.Value
End Sub

This is a forms combobox, it would not have a tooltip capability, but you can make it look like it has a tool tip.
Place a hyperlink with a screen tip underneath the combobox, when you mouse over the combobox the screen tip will pop up.
You can place the hyperlink on many cells if you intend on stretching the combobox over many cells.
Like this
Here is a 20 second clip
http://www.screencast.com/t/ZbkEOyXntItk
You can get the range of the combobox with application.caller.
Assign each combobox to this macro, then you would only need one macro.
Sub DoIt()
Dim r As Range
r = ActiveSheet.Shapes(Application.Caller).TopLeftCell
ActiveSheet.Hyperlinks.Add Anchor:=r, Address:=r, ScreenTip:="5435435345", TextToDisplay:="ddddddddddddddddddd"
End Sub

Following is my code:
Private Sub ComboBox1_Click()
' Adding new items
ComboBox1.AddItem ("S")
ComboBox1.AddItem ("M")
If ComboBox1.Text = "S" Then 'Add your dropdown item here
With Me.ComboBox1
.ControlTipText = "Strong" ' Add your text here
End With
End If
If ComboBox1.Text = "M" Then 'Add your dropdown item here
With Me.ComboBox1
.ControlTipText = "Moderate" ' Add your text here
End With
End If
End Sub

Related

How to programmatically add values to a listbox in a worksheet, not on UserForms?

I would like to programmatically add values to a listbox that I inserted inside an Excel worksheet. I've tried searching up for a solution online but all I see are solutions meant for UserForms, not for Worksheets. Am I missing something?
There are two types of listbox controls you can add to a worksheet.
With a Form Control, the content content is set via the input range, which contains range of values in a worksheet. For example:
If the listbox is an ActiveX control, you can refer to it in code via the worksheet that it is placed on, for example:
Public Sub UpdateListBox()
With Sheet1.ListBox1
.AddItem "A1"
.AddItem "B2"
.AddItem "C3"
End With
End Sub
Try following codes:
Sub AddItemToListBox()
With Sheet1.ListBox1
.AddItem "Paris"
.AddItem "New York"
.AddItem "London"
End With
End Sub
See these article for more details.
Article Link 1
Article Link 2
Assuming you are using List Box under Form Controls in a Worksheet, you can manually refresh data given the name of the List Box, you can extend it further to accept input of different datatypes. I am making use of non-intelli collection ListBoxes in my code. Note it takes the first name-matched listbox in the workbook.
In a separate Module:
Option Explicit
Sub RefreshListBox()
Dim oListBox As ListBox
Set oListBox = GetListBox("List Box 1")
If Not oListBox Is Nothing Then
With oListBox
.RemoveAllItems ' Clears old items
.AddItem "Item 1"
.AddItem "Item 2"
.AddItem "Item 3"
End With
End If
Set oListBox = Nothing
End Sub
Private Function GetListBox(ListboxName As String) As ListBox
Dim oWS As Worksheet, oLBox As ListBox
On Error Resume Next
For Each oWS In ThisWorkbook.Worksheets
If oWS.ListBoxes.Count > 0 Then Set oLBox = oWS.ListBoxes(ListboxName)
If Not oLBox Is Nothing Then Exit For
Next
Set GetListBox = oLBox
End Function

How to add a label and textbox based on combo box selection on a userform in excel

I am currently working on a userform to create an order for users at a company to send to my dept.
At the moment i have come to a standstill as i am struggling to work out the following.
I have a combobox which has a list of products our business offers. Based on the selection i want to be able to add labels and textbox which require the user to enter data for example.
If this selection in the combo box then
Enter name, date required, location of user etc.
Also this needs to be specific to the combobox selection.
Any help would be much appreciated :)
UPDATE
Apologies, as i did not have any code for that function I did not add any Here is the code i have.
Private Sub CommandButton1_Click()
Windows("RFS User Form Mock.xlsm").Visible = True
End Sub
Private Sub LegendDefinition_Change()
LegendDefinition.Locked = True
End Sub
Private Sub RequestList_Change()
Dim i As Long, LastRow As Long
LastRow = Sheets("Definition").Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Sheets("Definition").Cells(i, "A").Value = (Me.RequestList) Then
Me.DefinitionBox = Sheets("Definition").Cells(i, "B").Value
End If
Next
End Sub
Private Sub RequestList_DropButtonClick()
Dim i As Long, LastRow As Long
LastRow = Sheets("Definition").Range("A" & Rows.Count).End(xlUp).Row
If Me.RequestList.ListCount = 0 Then
For i = 2 To LastRow
Me.RequestList.AddItem Sheets("Definition").Cells(i, "A").Value
Next i
End If
End Sub
Sub UserForm_Initialize()
SiteList.List = Array("Birmingham", "Bristol", "Cardiff", "Chelmsford", "Edinburgh", "Fenchurch Street", "Glasgow", "Guernsey", "Halifax", "Homeworker", "Horsham", "Ipswich", "Jersey", "Leeds", "Leicester", "Lennox Wood", "Liverpool", "Manchester", "Peterborough", "Redhill", "Sunderland", "Madrid")
End Sub
Private Sub VLookUp_Change()
VLookUp.Locked = True
End Sub
When posting a question, you are expected to provide some code showing where you're standing trying to address the problem. Here's nevertheless a short demo that will give you a starting point.
Create a new UserForm and put a combobox, a label and a textbox on it; ensure they're named ComboBox1, Label1 and TextBox1, respectively.
Then, paste this code in the form's module:
Option Explicit
Private Sub ComboBox1_Change()
Dim bVisible As Boolean
'Only show the label and the textbox when the combo list index is 1, which corresponds to "Item 2".
'Note: bVisible = (ComboBox1.Text = "Item 2") would also work.
bVisible = (ComboBox1.ListIndex = 1)
Label1.Visible = bVisible
TextBox1.Visible = bVisible
End Sub
Private Sub UserForm_Layout()
'Populate the combo.
ComboBox1.AddItem "Item 1", 0
ComboBox1.AddItem "Item 2", 1
'Note: the code below could be removed by setting the corresponding
'design-time properties from the form designer.
ComboBox1.Style = fmStyleDropDownList
Label1.Visible = False
TextBox1.Visible = False
End Sub
Then press F5 to show the form. You'll notice that the label and textbox are only visible when the combo shows "Item 2". The visibility adjustment is performed within the ComboBox1_Change event handler.
If you plan on having numerous controls shown / hidden depending on your combo's value, you could group them into one or more Frame controls, and show / hide those frames instead.

Property "RowSource" Fails to Display on Combo Box

If I set the .RowSource property of a ListBox to a Named Range then in both the VBA display of the UserForm and the Excel display of the UserForm the row sources can be selected. However, with the ComboBox I only see this on the VBA display. If after setting the .RowSource property I try to .AddItem to the ComboBox object I get run time error 70, permission denied.
Private Sub UserForm_Initialize()
With pres_unit
.AddItem "kPa"
.AddItem "bar"
End With
End Sub
How can I use a named range as a source for the drop down options of a ComboBox?
If you are using a NamedRange for a single Column, you can use the List property of the ComboBox:
Private Sub UserForm_Initialize()
' create the Named Range "myNameRange"
' you can manually (or with variables) modify the Range("B2:B10") in "Sheet1"
ThisWorkbook.Names.Add "myNameRange", Sheets("Sheet1").Range("B2:B10")
With pres_unit
.List = Range("myNameRange").value
'disallows user input, only values from list
.Style = fmStyleDropDownList
End With
End Sub

Cell value upon checked box copied into Userform Textbox

I have several sheets of which house numerous checkboxes,of which when ticked, the value of cells next to the checkboxes will be copied into a textbox.Currently using ActiveX Textbox, below codes work just fine
Sub checkBoxHandler()
ActiveSheet.TextBox1.Text = ActiveSheet.TextBox1.Text & " " & ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(1, 1).Value
End Sub
But now i would like to use Userform Textbox since it can float on the workbook. Modification to the codes such as below does not do the trick (the value of cells next to the ticked checkboxes are not copied into the Userform Textbox).
Sub ShowTextBox()
UserForm1.TextBox1.Text = UserForm1.TextBox1.Text & vbLf & ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(1, 1).Value
UserForm1.Show vbModeless
End Sub
Does anybody know how to make it works?
I've done a similar project. I think userform does not support that kind of method. so i did this:
i put activex textbox on each of the sheets and named it accordingly (Textbox1,Textbox2..), and set the Visibility property to False
i assign macro (below) to a shape to pass the value of activex textbox to the Userform on every sheet :
Sub hocmsummary()
UserForm1.TextBox1.Text = UserForm1.TextBox1.Text & ActiveSheet.TextBox2.Text
End Sub
Remember to change the Textbox name accordingly.

Excel Combo Box Refresh Dropdown?

Is there a way to refresh a combobox?
I have the following VBA code. The dropdown is populated, until the If statement where the list is cleared and populated with the matched items.
At this point, the dropdown list only shows a single item with a scroll bar. But If I close the pulldown and reopen, it's fully populated correctly.
Private Sub ComboBox_SiteName_Change()
ComboBox_SiteName.DropDown
Dim v As Variant, i As Long
With Me.ComboBox_SiteName
.Value = UCase(.Value)
If .Value <> "" And .ListIndex = -1 Then
v = Worksheets("Address").Range("Table5[[#All],[SITE NAME]]").Value
.Clear ' Clear all items
' Repopulate with matched items
For i = LBound(v, 1) To UBound(v, 1)
If LCase(v(i, 1)) Like "*" & LCase(.Value) & "*" Then
.AddItem v(i, 1)
End If
Next i
Else
' Repopulate with all items
.List = Worksheets("Address").Range("Table5[[#All],[SITE NAME]]").Value
End If
End With
End Sub
The ComboBox_Change function gets called as the user types in the combo box.. the dropdown box turns from a list into a single line with Up/Down arrows after the Clear and Repopulate matched items..
but if I close the dropdown portion and reopen it lists all the items without Up/Down arrows.
The .ListRows value = 8 by the way.
I would like a way for the dropdown potion to either close and reopen.. or a VBA function to refresh the dropdown portion, Without external buttons or controls Please
Getting the list to ONLY show values that matched the text typed by the user so far, was a nightmare. Below is what I wrote which works (but took me a while!)
Note that the MacthEntry Property of the combo box MUST be set to "2 - frmMatchEntryNone" for the code to work. (Other values cause the combo box .value property store the text of the first value that matches what the user typed, and the code relies on it storing what they typed.)
Also note, the trick to get around the behaviour you observed, ie the combo boxes list of values not being sized correctly, was to use the code lines:
LastActiveCell.Activate
ComboBox_SiteName.Activate
Also, the code will pick up any items on the list that have the letters typed by the user ANYWHERE in their text.
Anyway, here's my code:
Private Sub ComboBox_SiteName_GotFocus()
' When it first gets the focus ALWAYS refresh the list
' taking into acocunt what has been typed so far by the user
RePopulateList FilterString:=Me.ComboBox_SiteName.Value
Me.ComboBox_SiteName.DropDown
End Sub
' #4 Private Sub ComboBox_SiteName_Change()
Private Sub ComboBox_SiteName_Enter()
Dim LastActiveCell As Range
On Error GoTo err_Handler
Set LastActiveCell = ActiveCell
Application.ScreenUpdating = False
With Me.ComboBox_SiteName
If .Value = "" Then
' Used cleared the combo
' Repopulate will all values
RePopulateList
.DropDown
Else
' #4 reducdant
' LastActiveCell.Select
' .Activate
' ===========================================
' #4 new code
' CheckBox1 is another control on the form
' which can receive the focus and loose it without event firing
CheckBox1.SetFocus
' This will trigger the GotFocus event handler
' which will do a refresnh of the list
.SetFocus
' ===========================================
End If
End With
Application.ScreenUpdating = True
Exit Sub
err_Handler:
Application.ScreenUpdating = True
Err.Raise Err.Number, "", Err.Description
Exit Sub
Resume
End Sub
Private Sub RePopulateList(Optional FilterString As String = "")
Dim i As Long
Dim ValidValues() As Variant
' #2 range now refers to just the data cells
ValidValues = Worksheets("Address").Range("Table5[SITE NAME]").Value
With Me.ComboBox_SiteName
If FilterString = "" Then
' All all values
.List = ValidValues
Else
' #2: .List cannot be set to have no items.
' so remove all but one
.List = Array("Dummy Value")
' Only add values that match the FilterString parameter
For i = LBound(ValidValues, 1) To UBound(ValidValues, 1)
If LCase(ValidValues(i, 1)) Like "*" & LCase(FilterString) & "*" Then
.AddItem ValidValues(i, 1)
End If
Next i
' #2 add this line to remove the dummy item
.RemoveItem (0)
End If
End With
End Sub
Private Sub ComboBox_SiteName_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Application.ScreenUpdating = False
End Sub
======================================================================
You could: Replace all your code with this which should give acceptable functionality (as long a the data source is in alpha order), and it's easy! However, it doesn't quite do what you wanted.
Private Sub ComboBox_SiteName_GotFocus()
With Me.ComboBox_SiteName
.List = Worksheets("Address").Range("Table5[[#All],[SITE NAME]]").Value
End With
ComboBox_SiteName.DropDown
End Sub
Combo boxes can be set up to "filter as the user types" - so long as the data is in alphabetical order.
======================================================================
Note that in your code the following two lines cause the ComboBox_SiteName_Change event to start again. I suspect you need to add break points and debug you code more.
.Value = UCase(.Value)
.Clear ' Clear all items
Anyway, I hope this is job done.
this will be my first bounty if I get it, so please let me know if you need any more help. (I think it may be worth more than 50 points)
Harvey
================================================
PART 2:
To answer you comment issues:
(See the #2 tag in my code above)
To refer to a table column's data, excluding the header use:
=Table5[SITE NAME]
(This will be autogenerated when entering a formula if you click and drag over the data cells in a column).
The code has been altered accordlingly.
I used excel 2013 and 2010 and found that the .Activate event works in both.
See #3 for a minor change.
Please recopy all the code.
note that I introduced code to try and stop flickering using Application.ScreenUpdating, but it didn;t have any effect - I don't know why. I've left the code in so you can do further experiments should you need to.
NOTE the new procedure ComboBox_SiteName_KeyDown
================================================
PART 3:
To answer you comment issues:
It's a combo on a form ! - so make the change tagged with #4 above.
Harvey
Solved!
https://trumpexcel.com/excel-drop-down-list-with-search-suggestions/
You can do what is in the link with some modifications:
"ListFillRange" in combobox properties should be the last column (the one that is changing). If it is a userform the range will go under "RowSource".
And add this code:
Private Sub ComboBox1_Change()
Sheets("Where the data is").Range("B3") = Me.ComboBox1.Value
End Sub
Try changing the command from Change to DropButtonClick
This refreshes the list on a click of the drop down

Resources