I have search for the same question, and I saw a few of the similar post, however my Userform still can't work. I am new to VBA and Userform.
I have a total of 12 Checkboxes (12 Months), and I have to check that at least one of the CheckBox is checked.
Dim atLeastOneChecked As Boolean
atLeastOneChecked = False
Dim ctrlNCK As Control
For Each ctrlNCK In Controls
If TypeName(ctrlNCK) = "chkMonth" Then
If ctrlNCK.Value = True Then atLeastOneChecked = True
End If
Next ctrlNCK
If Not atLeastOneChecked = True Then
MsgBox "Month cannot be empty.", vbExclamation, "Input Data"
Exit Sub
End If
This is untested, but try:
If Left(ctrlNCK.Name,8) = "chkMonth" Then
I wouldn't ever expect the Type to be "chkMonth". This assumes that each relevant CheckBox name starts with "chkMonth".
If you only ever want one, and only one, month chosen, I'd consider using OptionButtons in a Frame.
If (chbindian + chbchinies + chbitalian + chbsindian) = 0 Then
MsgBox "Please select at least Two checkbox"
Exit Sub
End If
try this
(chbindian + chbchinies + chbitalian + chbsindian) replace this names with your checkbox name
Using similar approach to the question code I came up with this:
Private Sub CommandButton1_Click()
Dim chk As Control
Dim i As Long
For Each chk In Me.Controls
If TypeOf chk Is MSForms.CheckBox Then
If chk = 0 Then
i = i + 1
End If
End If
Next
If i = 12 Then
MsgBox "Please select at least one month!"
Exit Sub
End If
MsgBox "You selected at least one month!"
End Sub
To explain:
The For loop is checking one by one each CheckBox on the UserForm.
If the value of the CheckBox is 0 (False) then the counter which is the i variable equals it's own value at the end of the previous iteration (current value) + 1.
Each CheckBox with a value of 0 (False) meaning it's 'unchecked' adds 1 to the counter and thus, once the loop is complete i will equal anywhere between 0 (all CheckBoxes are checked) and 12 (no CheckBoxes are checked).
After the loop is exited the next if statement checks if the value of the counter i is equal to 12 then a MsgBox displays "Please select at least one month!" otherwise whatever is meant to happen next will now execute (In my example its another MsgBox advising "You selected at least one month!").
NOTE: If more CheckBoxes were added to the UserForm at a later time for whatever reason, my solution would be flawed as it will check ALL CheckBox commands on the form.
To work around that you can put the required CheckBoxes on a Frame on the UserForm.
Assuming the Frame is named Frame1 all you would need to do is adjust the For line to specify for each CheckBox in Frame1 on the UserForm like so: For Each chk In Me.Frame1.Controls
Related
I have add a ListBox from Active X Controls in my Excel File and made it a multi select box with checkboxes.
I have also added a selection change event in the VB script against this list box.
Sub lstMultiSelectBox_Change()
If blnCheck = False Then
CheckAll
End If
End Sub
Now what I am struggling to find is that which item was last checked. With this information I want to implement Select All and Un Select All feature in this list box.
In order to make ListBox1_Change event returning the last selected list box value, you can use the solution. It can detect the selected value, independent of its position in the list:
Create a Private variable on top of the sheet module where the list box exists (in the declarations area):
Private colS As New Collection
Then copy the next adapted event code:
Private Sub ListBox1_Change()
Dim i As Long
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
If colS.Count = 0 Then
colS.Add ListBox1.List(i), ListBox1.List(i)
Else
If Not itExists(colS, ListBox1.List(i)) Then
colS.Add ListBox1.List(i), ListBox1.List(i)
End If
End If
Else
If itExists(colS, ListBox1.List(i)) Then
colS.Remove ListBox1.List(i): Exit Sub
End If
End If
Next i
If colS.Count > 0 Then MsgBox colS(colS.Count)
End Sub
If you want it triggering only if the selected value is "Select All", then replace the last event code line with something like:
If colS.Count > 0 Then
If colS(colS.Count) = "Select All" then
'do whatever you need in such a case
'but, if you try selecting all of lines, in order to avoid the event
'being triggered again, you should use 'Application.EnableEvents = False`, before selecting and 'Application.EnableEvents = True` after
End If
End If
The simplest solution should be the one suggested in the first comment:
If Listbox1.Selected(1) = True Then
'do whatever you need
End If
But, in order to make it working as it should, the line "Select All" should be the second of the list...
I have this code but it only work for my first row.
It is suppose to look if the checkbox on B, C or D is checked, and if so, a date + username will automaticaly fill in F and G.
here is a picture of my table:
This is what my code looks like:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("B2") Or Range("C2") Or Range("D2") = True Then
Range("G2").Value = Environ("Username")
Range("F2").Value = Date
Else
Range("F2:G2").ClearContents
End If
End Sub
Enter this code in a regular module, select all your checkboxes and right-click >> assign macro then choose ReviewRows.
This will run the check whenever a checkbox is clicked - a bit of overhead since all rows will be checked, but should not be a big deal.
Sub ReviewRows()
Dim n As Long
For n = 1 To 100 'for example
With Sheet1.Rows(n)
If Application.CountIf(.Cells(2).Resize(1, 3), "TRUE") > 0 Then
If Len(.Cells(6).Value) = 0 Then 'only enter if currently empty?
.Cells(6) = Date
.Cells(7) = Environ("Username")
End If
Else
.Cells(6).Resize(1, 2).ClearContents
End If
End With
Next n
End Sub
If you want to be more precise then Application.Caller will give you the name of the checkbox which was clicked, and you can use that to find the appropriate row to check via the linkedCell.
Sub ReviewRows()
Dim n As Long, shp As CheckBox, c As Range, ws As Worksheet
Set ws = ActiveSheet
On Error Resume Next 'ignore error in case calling object is not a checkbox
Set shp = ActiveSheet.CheckBoxes(Application.Caller) 'get the clicked checkbox
On Error GoTo 0 'stop ignoring errors
If Not shp Is Nothing Then 'got a checkbox ?
If shp.LinkedCell <> "" Then 'does it have a linked cell ?
With ws.Range(shp.LinkedCell).EntireRow
If Application.CountIf(.Cells(2).Resize(1, 3), "TRUE") > 0 Then
If Len(.Cells(6).Value) = 0 Then 'only enter if currently empty?
.Cells(6) = Date
.Cells(7) = Environ("Username")
End If
Else
.Cells(6).Resize(1, 2).ClearContents
End If
End With
End If 'has linked cell
End If 'was a checkbox
End Sub
However this appraoch is sensitive to the exact positioning of your checkbox
You have a long way to go!
Unfortunately, If Range("B2") Or Range("C2") Or Range("D2") = True Then is beyond repair. In fact, your entire concept is.
Start with the concept: Technically speaking, checkboxes aren't on the worksheet. They are on a layer that is superimposed over the worksheet. They don't cause a worksheet event, nor are they responding to worksheet events. The good thing is that they have their own.
If Range("B2") Or Range("C2") Or Range("D2") = True Then conflates Range with Range.Value. One is an object (the cell), the other one of the object's properties. So, to insert sense into your syntax it would have to read, like, If Range("B2").Value = True Or Range("C2").Value = True Or Range("D2").Value = True Then. However this won't work because the trigger is wrong. The Worksheet_Change event won't fire when when a checkbox changes a cell's value, and the SelectionChange event is far too common to let it run indiscriminately in the hope of sometimes being right (like the broken clock that shows the correct time twice a day).
The answer, therefore is to capture the checkbox's click event.
Private Sub CheckBox1_Click()
If CheckBox1.Value = vbTrue Then
MsgBox "Clicked"
End If
End Sub
Whatever you want to do when the checkbox is checked must be done where it now shows a MsgBox. You can also take action when it is being unchecked.
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
I have an Excel UserForm, which submits data to a worksheet. I have built in data validation that requires each text box to have a value entered, e.g.:
Private Sub Button_Submit_Click()
'Data Validation
If Me.txtCVS.Value = "" Then
Me.txtCVS.SetFocus
MsgBox "'CVs Screened' is a mandatory field. Enter daily figure or zero.", vbOKOnly, "Required Field"
Exit Function
However, I don't know what code to use to require a selection from a list box - users select their name from the list box before entering in their daily figures. Some users, it seems, can't remember to click their name(!!!).
Does anybody have a piece of workable code I can use to require a selection before submitting results? It doesn't seem to work in the same way as the text box text above.
You can use the below function which iterates through all the items in the listbox and returns true/false if anything is selected or not.
Private Sub Button_Submit_Click()
If Not IsAnythingSelected(ListBox1) Then
MsgBox "Please select your name"
End If
End Sub
Function IsAnythingSelected(lBox As Control) As Boolean
Dim i As Long
Dim selected As Boolean
selected = False
For i = 1 To lBox.ListCount
If lBox.selected(i) Then
selected = True
Exit For
End If
Next i
IsAnythingSelected = selected
End Function
Try changing
For i = 1 to lBox.ListCount
to the following:
For i = 0 To lBox.ListCount - 1
a question is : how to load a or give value to a combo box list and then call it in my worksheet and get the selected value from it ?i have a module that i want to call my userform1 which include the combobox in it . but when i debug the program it is just a show of the combo box . i think it doesn't do anything ... thanks for your time ..this is the code for user form:
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "weibull"
.AddItem "log-normal"
.AddItem "gambel"
.Style = fmStyleDropDownList
End With
End Sub
and this is how i ask in my sub to show the combobox:
UserForm1.Show
If ComboBox1.ListIndex = -1 Then
MsgBox "There is no item currently selected.", _
vbInformation, _
"Combo Box Demo"
Exit Sub
End If
MsgBox "You have selected " & ComboBox1.List(ComboBox1.ListIndex) & "." & vbNewLine _
& "It has " & ComboBox1.ItemData(ComboBox1.ListIndex) ", _
vbInformation, _
"Combo Box Demo"
the second part is what i found in net , but it made the program at least to show the combo box !
I thought Siddharth's answer was pretty clear particularly as it was posted from a mobile! However, I had an email from the OP saying he did not understand the answer. I provided the following background which was apparently sufficient to allow him to understand Siddharth's answer and solve his problem. I post it here for the benefit of any other visitor who needs more background on forms than Siddharth provides.
If you select VBA Help and type “userform show” you will get a description of the Show command.
If your user form is named “UserForm1”, you can have statements:
UserForm1.Show
UserForm1.Show vbModal
UserForm1.Show vbModeless
Statements 1 and 2 are equivalent.
The choice of VbModal or vbModeless completely changes the way the user form is controlled.
If a form is shown modeless, the user can see it but cannot access it. If I have a macro that takes a long time, I will use a modeless form to show progress. If I am working down the rows of a large worksheet I might have a form containing:
I am working on row nnnn of mmmm
Each of the boxes is a label. I set the value of the label containing “mmmm” to the number of rows when I start the macro. I set the value of the label containing “nnnn” to the row number at the start of each repeat of my loop. The user sees:
I am working on row 1 of 5123
then I am working on row 2 of 5123
then I am working on row 3 of 5123
and so on.
If it takes the macro five minutes to process every row, this tells the user that something is happening. Without the form, the user might think the macro had failed. With the form, the user knows the macro is busy and they have time to get a fresh cup of coffee.
On the other hand, if the form is shown modal, the macro stops until the user does something that closes or unloads the form with a statement such as:
Unload Me
The positioning of this statement depends on your form. I normally have a Submit button that saves information before ending with this statement.
Once the Unload Me statement is executed, the macro restarts at the statement after the Show statement. When the macro restarts, the form has gone. This is why the form must save anything the macro needs in global variables.
You are trying to access a control when the userform is already closed. And I say closed becuase you are not using vbmodeless to show the form. So the only way the next line after that can run is when the form is closed. Here is what I recommend.
Declare public variables in a module which will hold the relevant values when the useform closes and then use that later. For example
Paste this code in the userform
Option Explicit
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "weibull"
.AddItem "log-normal"
.AddItem "gambel"
.Style = fmStyleDropDownList
End With
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If ComboBox1.ListIndex <> -1 Then
SelectItem = ComboBox1.List(ComboBox1.ListIndex)
pos = ComboBox1.ListIndex + 1
End If
End Sub
And paste this in a module
Option Explicit
Public SelectItem As String, pos As Long
Sub Sample()
'
'~~> Rest of your code
'
SelectItem = "": pos = 0
UserForm1.Show
If pos = 0 Then
MsgBox "There is no item currently selected.", _
vbInformation, "Combo Box Demo"
Exit Sub
End If
MsgBox "You have selected " & SelectItem & "." & vbNewLine & _
"It is at position " & pos, vbInformation, "Combo Box Demo"
'
'~~> Rest of your code
'
End Sub
Also
There is no .Itemdata property of the Combobox. It is available in VB6 but not in VBA. With .Itemdata property of the Combobox, I guess you were trying to get the position?