how to add item to a combobox on button click? - excel

I want to add item to a combobox found in excel worksheet from text box which is located in the user form When button is clicked.i see the value added to combobox but it will become empty when I close and reopens the workbook.can any one help me handling this?
Thank u for you're fast response first
thank you both for your feedback and correction.let me make more clear my concern

Create a workbook and save as xlsm.
On the first worksheet define user name as follows:
Name: dn_cmb_items
Range: =""
Using the developer ribbon add an Excel (not ActiveX) combobox onto the Worksheet1 and set its list-by-range to dn_cmb_items
Open VBA editor and add a user form to the workbook, name it as frm_add_cmb_item and set ShowModal to False.
Drop a text box to the form and name it tb_item_text.
Drop a button to the form, name it cmb_add and from its context menu choose View code. This creates the click event handler.
Implement the handler as follows:
Private Sub cmb_add_Click()
Dim v_r As Range, v_n As Name
Set v_n = Names("dn_cmb_items")
If v_n.Value = "=""""" Then
v_n.Value = "=" & Worksheets(1).Name & "!$A$1:$A$1"
v_n.RefersToRange.Value = tb_item_text.Text
Else
Set v_r = v_n.RefersToRange
Set v_r = v_r.Cells(v_r.Rows.Count + 1, 1)
v_r.Value = tb_item_text.Text
v_n.Value = "=" & Worksheets(1).Name & "!$A$1:" & v_r.Address(True, True)
End If
End Sub
Drop onto the workshet a button, then create/set a macros in the workbook. Implement the created macros with the code frm_add_cmb_item.Show.
In the VBA Editor from the Debug menu choose Compile. Then save the VBAProject as well as the workbook. That's all for the coding.
Switch to the worksheet, show the form.
Now when you enter some to the textbox, then click the cmb_add button, a new item will be added to the A column at the end thus changing the value of dn_cmb_items assigned to the combobox on the worksheet.
See the screenshorts attached:
Initial state:
1 added:
2 added:
PS
I have the ready workbook with all the code. Where should I upload it?

Be specific with your question and always post the relevant code, so that it will become easy to solve it for others.
If you want to see the data while executing the userform, just write the required data in userform_activate or Initialize. before executing it will take the values and shows up in the combobox.
the input which you are taking from the worksheet just write those values in another worksheet so that whenever you open the workbook the values will not get erased.

Related

How to find last empty row among many named ranges in worksheet and push the textbox value for selected named range without showing worksheet

off late I got developed interest in excel VB applications and practicing it since last 2 years. ( I use Excel 2016 version )
I have a problem with my recent Vb program. I have designed a main Userform with two ComboBoxes and out of it, ComboBox2 list is depending on ComboBox1 value.
For ComboBox1 row source, I have linked it to one of the named ranges in worksheet Sheet4("Settings") ColumnB which is actually the list of process names and in same sheet # different columns I have many named ranges (task list) bearing the name of all the items listed for ComboBox1 as headings.
So when I choose list in ComboBox1 dropdown , (Process names, which is also named range) only the relevant options will appear in ComboBox2 (task item) and upto this file is working fine.
Now to add more task line items to named ranges which will appear in combobox2 , I have designed another Userform (2nd one)so that user can add more task options himself under any selected process and he don't have to approach me.
So what I did, in a 2nd Userform I added combobox3 and TextBox1 with submit button. The Combobox3 will show same list as ComboBox1 does -Process names.
Intention of 2nd Userform is when user select process name from Combo3 followed by new task list entered in textbox1 and after submitting, Vb will look for named range selected in combo3, should go to worksheet "Settings" and find empty row in selected process range and will push the value of textbox1-task item. So that user will be able to get newly added value under his selected process in a main Userform.
But the problem is here, while operating the file the excel file is to set to show only Userform, to feel like App and will not display any worksheets during Userform operation. (No excel environment)
However while using 2nd Userform the code is forcing to display " Settings" worksheet (excel environment), since it is forbidden in code for not to navigate to excelworksheet, UF2 action failing in completing task.
However, If I keep Worksheets displaying in background (& 2nd Userform in front) then no issue, I was able to append the textbox1 value to desired named ranges in " Settings" ws.
The Error i get while using 2nd Userform without having excel sheets Opened is : " Run-time Error '1004' , Select method of Range class failed" . I tried using " application.screenUpdate=False/True", but no use, code stops working, unless excel worksheet is displayed...
any help in this regard will be appreciated
Code written :
Private Sub UserForm2_Initialize() ' UF name "addCat"
Dim i As Long
For i = 2 To Sheet4.Range("B50").End(xlUp).Offset(1, 0).Row
Me.SelFnCB.AddItem Sheet4.Cells(i, 2).Value
Next i
End Sub
'---------------------------------------------------------------
Private Sub CatUpdtCmd_Click() 'this is to add new items under selected namedRanges in worksheet
Dim lastRow As Long
Dim ws As Worksheet
i = Me.SelFnCB.Value 'Combobox 3 value with process names as named Range
Set ws = Worksheets("Settings")
Worksheets("Settings").Unprotect "Bnm0000"
Range(i).Select ' at this stage of code execution , screen tries physically go to worksheet and tries to display it.which i dont want.
Range(i).Find("").Activate
ActiveCell.Value = Me.NwCat.Value '( "NwCat" is TextBox1 with new task to be added to selected named range)
Worksheets("Settings").Range("A1").Select
Worksheets("Settings").Protect "Bnm0000"
Me.NwCat.Value = ""
ActiveWorkbook.Save
MsgBox " Done, Select the process again to view your update ", vbInformation, Title:=" Category added "
Unload Me
addCat.Show
End Sub

Detect ComboBox Change Excel VBA

I have a sheet with a bunch of ComboBoxes(form control) and I want to detect when a user changes any one of them and write text in a cell. Using Worksheet_Change on the target cells doesn't work. I have tried a bunch of things that don't work. I'm not sure what needs to be in the private sub line or the if statement.
Private Sub DropDowns_DropButtonClick()
If ActiveSheet.DropDowns.Value > 1 Then
Cells(13, 5).Font.Bold = True
Cells(13, 5).Font.Color = vbRed
Cells(13, 5).Value = "!!! Selections have been changed. !!!"
End If
End Sub
I have tried
ComboBox_AfterUpdate()
ComboBox_Change()
DropDowns_AfterUpdate()
DropsDowns_Change()
and anything else I could find. I've also tried a few different things in the if statement with no luck.
I appreciate any help.
Chris
If I'm reading you correctly, you're comboboxes are in a userform. If I'm correct, simply open your userform in 'Visual Basic' and double click on the relavant combobox. This will open the code pane and create an empty Private Sub routine called 'Private Sub <Combobox Name> ()'.
Enter your code to place your data in the sheet (or whatever else you want) into the subroutine and Bob should be your uncle.
Apologies in advance if there's something I've missed.
RannochRob
Edit...
OK, my mistake, it's a form control.
My first comment is that it's easier to use an activex control if you can... however, with a form control, should (a) Use the cell link box in the 'Format Control' drop down ('Control' tab) to place the result in a cell... however, that result will not be the content of the box but an integer equal to the position of the selected entry on the list of entries in the combobox. You then need to (b) assign a macro to the combobox which will pick up the result and use it to get the required information from the range containing the list of entries. Like I say, much easier with an activex control...
RannochRob
Here's how you can do it by assigning a macro to the combobox (right click on the combobox>assign macro) as #BigBen mentioned in the comments section:
Option Explicit
Sub DropDown1_Change()
Dim sht As Worksheet
Dim dd As DropDown
Set sht = ThisWorkbook.Worksheets("Name of your Worksheet") 'Name of the worksheet in which the combobox is located
Set dd = sht.DropDowns("Drop Down 1") 'name of your combobox
sht.Range("G1").Value = "The selected value is: " & dd.List(dd.Value) 'dd.value returns the index of the selected value
End Sub
You can use the same code for each one of your comboboxes.
For demonstration purposes i have used the following set-up:
You can easily modify the code to best fit your needs.

ActiveX Command Button combined with ActiveX List Boxes – VBA Code Needed

I would like to create an ActiveX Command Button that will populate cells on one worksheet based off of data from a separate, hidden sheet (still in the same workbook though). However, I want the button to know to pull specific data depending on selections that were chosen in list boxes.
For example: Let’s say someone is working in “Worksheet 1,” where 2 ActiveX List Boxes and 1 ActiveX Command button are located. If this individual chooses “Animal” in the first list box, then the second list box will display a following list of animals. Then, let’s say that person chooses “dog” in the second list box. I then want the ActiveX Command Button to recognize that someone chose both “animal” and “dog” in the two previous list boxes, and then when clicked, be able to pull data from a separate hidden sheet (“Worksheet 2”) to display on “Worksheet 1.” So, in other words the data for the selection “dog” would be hidden away from the individual, but when they choose “dog” in the second list box, and then click the ActiveX command button, then the data would appear.
I already know how to write the code in VBA for dependent list boxes, but I am unsure on how to make an ActiveX Command Button dependent upon selections in a list box. Is this possible, and if so, can anyone provide me with a VBA code that I can use to fulfill my specifications? Furthermore, does anyone know a VBA code for an ActiveX Command Button that will pull data from one sheet, and display it on another? Any input is appreciated. Thanks!
Hard to be specific with the info given, but hopefully this can point you in the right direction. This assumes that you only have one column in your 2nd ListBox:
Sub cmdActiveX_Click()
Dim strBox1 as String
Dim strBox2 as String
strBox1 = Worksheets("SheetWithListBoxes").ListBox1.List(Worksheets("SheetWithListBoxes").ListBox1.ListIndex))
End Sub
A cleaner way might be:
Sub cmdActiveX_Click()
Dim lbo as ListBox
Dim strBox1 as String
Set lbo = Worksheets("SheetWithListBoxes").ListBox1
strBox1 = lbo.List(lbo.ListIndex)
End Sub
So, you get the selected item's index from ListIndex, and then you pass that to the List method. This also assumes that MulitSelect is off (single).
Have fun!
Well, I believe I actually found a way to have the Command Button pull data from one sheet and place it on another sheet by creating this module:
Sub PopulateMain(ByVal lRowNumber As Long)
Dim shReport As Worksheet
Dim shData As Worksheet
' Assign sheets to the variable.
Set shReport = ThisWorkbook.Worksheets("Report")
Set shData = ThisWorkbook.Worksheets("Data")
' Paste the value in sheet Data Range H2 into sheet Report Range C12.
shReport.Range("C14").Value = shData.Range("H2").Value
shReport.Range("C16").Value = shData.Range("I2").Value
shReport.Range("C18").Value = shData.Range("J2").Value
shReport.Range("C20").Value = shData.Range("K2").Value
shReport.Range("K14").Value = shData.Range("L2").Value
shReport.Range("K16").Value = shData.Range("M2").Value
shReport.Range("K18").Value = shData.Range("N2").Value
End Sub
And then using this code:
Private Sub CommandButton1_Click()
Call PopulateMain(2)
End Sub
However, I still don't know how to link the Command Button to the List Boxes so that it knows a particular choice has been made. So, again, if someone chose "Animals" in the first box and "Dog" in the second box, I need the Command Button to recognize those two choices in order to pull the correct data from the hidden sheet.
Ok, try something like this (by the way, are these list boxes or combo boxes? Confused by your naming if they are list boxes or not...if combo, change the As ListBox to As ComboBox):
Sub cmdActiveX_Click()
Dim lboCategory as ListBox
Dim lboDependent as ListBox
Dim strBox1 as String
Set lboCategory = Worksheets("Report").cboCategoryList
strCategory = lboCategory.List(lboCategory.ListIndex)
Set lboDependent = Worksheets("Report").cboDependentList
strCategory = lboCategory.List(lboCategory.ListIndex)
End Sub
Then use the 2 string values to find your data...make sense?

Selected value in combo box to open another worksheet in Excel VBA/User form

How to apply another method after selecting the value from combo box?
I have a list of names in worksheet"Home" and for each name in Range "C" they were a single worksheet linked containing the information of that name as mention in the image.
Excel sheet picture
I did a user form containing a combo box and some labels referring to the user name information , I need when I select the user name from the combo box the excel will go and open the page of that user name and retrieve the information from there.
Userform
Also, I am facing a problem with selecting the names from "Home" page. I used this code
cboUserList.List = wsHome.Range("c12", Range("c12").End(xlDown)).Value
but it is showing Method 'Range' of object'-Worksheet'failed.
This is my code for the command button "Import"
Private Sub cmdImport_Click()
cboUserList.List = wsHome.Range("c12", Range("c12").End(xlDown)).Value
lstActivationDate.List = ActiveSheet.Range("h2", Range("h2").End(xlDown)).Value
lstPaidDate.List = ActiveSheet.Range("c2", Range("c2").End(xlDown)).Value
lblUserID.Caption = [f2]
lblsubscType.Caption = ActiveSheet.Range("i2").End(xlDown).Value
lblamount.Caption = ActiveSheet.Range("j2").End(xlDown).Value
lblamountpaid.Caption = ActiveSheet.Range("d2").End(xlDown).Value
lbldate.Caption = Format(Date, "dd-mmm-yyyy")
lbldebts.Caption = Range("f5:f6").Item(1).Value
lblNotes.Caption = [f13]
End Sub
One idea to get your code to work: Add wsHome to the second range too. cboUserList.List = wsHome.Range("c12", wsHome.Range("c12").End(xlDown)).Value
To populate the ComboBox try to use cboUserList.AddItem(<String>). Loop through your range to get all elements into the ComboBox. Alternatively try to to use an array containing your names with .List.
To switch to the Workbook of the User you have to use this piece of code in your userform code:
Private Sub cboUserList_Change()
Worksheets(Cstr(wsHome.Range("c12", wsHome.Range("c12").End(xlDown)).Find(cboUserList.Value, LookIn:=xlValues).Offset(0, 1).Value)).Activate
End Sub

Excel button that writes down the time of clicking

I want to make list of times in Excel Spreadsheets.
The idea is to have 4 buttons in the spreadsheet that will write down the time of clicking of each button.
Each button will represent a different group, and I wish to have a list of the times I pressed each button so I could check and research about the groups activity.
Create a new module in your VBE and stick this in there:
Sub capturetime()
Dim timeWS As Worksheet
Dim timeRange As Range
'Change "Sheet3" to whatever worksheet is your click log
Set timeWS = ThisWorkbook.Sheets("Sheet3")
'find the last cell in column A of your log
Set timeRange = timeWS.Range("A" & timeWS.Rows.Count).End(xlUp).Offset(1)
'Write which button was clicked in column A
timeRange.Value = Application.Caller
'Write the time in column B
timeRange.Offset(, 1).Value = Now()
End Sub
Edit the values as necessary in that code.
Create a button using Developer>>(Controls)Insert. Find the button in there. The "Form" button is fine.
Draw the button on the screen somewhere. And, when it prompts you to assign a macro, choose "capturetime"
This bit of VBA will grab the name of the button that was pressed and the time and write it to whatever worksheet you select as the your log. It's pretty simple, so it shouldn't be a bother to mess with it to fit your needs.

Resources