I am working on pulling data out of a standardized form in excel. There is a Forms Control CheckBox that I need the state of. Apparently the only way to get this is from the cell link, where the value is placed into a cell. The problem is, whomever put this form together did not set a cell link. Is there any way to do this using VBA at run time. There are many of these forms that I must go through, so I'm trying to avoid doing it manually.
I think you are referring to a forms checkbox control placed on a worksheet, in which case you can get the state of the control without setting a cell link. Like this:
Sub HTH()
Dim iLoop As Integer
'// Get value of check box by its index
MsgBox (GetCheckBoxState(1))
'// Get value of check box by its name
MsgBox (GetCheckBoxState("Check Box 1"))
'// Loop through all checkboxes and get values
For iLoop = 1 To ActiveSheet.CheckBoxes.Count
MsgBox (GetCheckBoxState(iLoop))
Next
End Sub
Function GetCheckBoxState(vCheckBox As Variant) As String
Select Case ActiveSheet.CheckBoxes(vCheckBox).Value
Case xlOn
GetCheckBoxState = "Checked"
Case xlOff
GetCheckBoxState = "UnChecked"
Case xlMixed
GetCheckBoxState = "Mixed"
End Select
End Function
If you are referring to a check box control on a userform then as Tim pointed out it should be a case of something like:
MsgBox (UserForm1.CheckBox1.Value)
Related
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.
I have looked at some examples for my question but couldn't find an answer that works.
Background:
I have a list of items (let's say apple, orange, banana) in Sheet1 (A2:A77, which is already a defined range with the name "Liste").
I then have on another sheet (Let's say Sheet2) with several cells where a userform (created with vba code) pops up where the user can choose an item and click OK.
However, due to the nature of the userform (and the list), you can have spelling errors etc and it will still be accepted. So I would like to create a check where it matches the input to the given list (to prevent users from putting anything else in). The userform/code is on purpose to keep it searchable (rather than just a simple data validation list).
Issue:
I tried to create this with vba code that checks the input, matches it to the Sheet1 list and if there is no match, shows a msgbox with a statement. This partially worked (for some letters but not others, very strange).
Here is the code I had:
Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Dim rSearchRng As Range
Dim vFindvar As Variant
If Not Intersect([B7:B26], Target) Is Nothing Then
Set rSearchRng = Sheet4.Range("Liste")
Set vFindvar = rSearchRng.Find(Target.Value)
If Not vFindvar Is Nothing Then
MsgBox "The Audit Project Name you have entered is not valid. Please try again!", vbExclamation, "Error!"
Selection.ClearContents
End If
End If
Application.EnableEvents = True
End Sub
So I was thinking of creating this error message instead with a simple data validation.
Data validation
I have tried the "list" option (and put it equal to the named range) but that did nothing (no error box showed up)
I have tried "Custom" with the following formula 'SUMPRODUCT(--(B12=Liste)>0)=TRUE (I found this on a post which worked for others when I tried it in the cell it gave me the expected "TRUE/FALSE" results) but still nothing shows up
UPDATE
Tigeravatars data validation recommendations work if you don't have a userform (see comments below).
For it to work with a UserForm, I changed the 'MatchEntry' to TRUE and also deleted any unwanted "change events" from my ComboBox code. The final code I use now is below:
Dim a()
Private Sub CommandButton2_Click()
End Sub
Private Sub UserForm_Initialize()
a = [Liste].Value
Me.ComboBox1.List = a
End Sub
Private Sub ComboBox1_Change()
Set d1 = CreateObject("Scripting.Dictionary")
tmp = UCase(Me.ComboBox1) & "*"
For Each c In a
If UCase(c) Like tmp Then d1(c) = ""
Next c
Me.ComboBox1.List = d1.keys
Me.ComboBox1.DropDown
End Sub
Private Sub CommandButton1_Click()
ActiveCell = Me.ComboBox1
Unload Me
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
I thought I show it here in case anyone stumbles across my question.
Thank you!
Select your cells where you want to put the data validation
With the cells selected, go to Data Tab -> Validation
Set "Allow" to "List" and set the Source to =Liste as shown here:
Next go to the "Error Alert" tab and set "Style" to "Warning" and enter the desired text in "Title" and "Error Message" as shown here:
Test it out. You should now have a drop-down list of valid choices, and if you attempt to manually enter an invalid choice you'll get the error message you specified.
As a note, if you want the data validation to completely disallow/prevent any entry not in the list, you'll need to set the Error Allert -> Style to be "Stop" instead of "Warning".
EDIT:
Per comments, it can't be a drop-down list. I highly recommend using a drop-down list for this because it will be the most effective way to cut down on time entering data as well as reduce errors from typos. However, if it absolutely cannot be a drop-down list, then you can use a Custom Data Validation and set the formula to =ISNUMBER(MATCH(B7,Liste,0)) (we are using B7 here because it is the first cell in the range of cells that contains this data validation).
Try the following formula:
=NOT(ISERROR(FIND("-"&A1&"-",(TEXTJOIN(,"-",TRUE,Sheet1!A1:A77)))))
That combines all the texts and then see if what's in the cell occurs in the list. I put it between dashes to prevent it from accepting partials.
I have 3 combo boxes which are dependent with each other. List on cmb2 depends on the value on cmb1. cmb3 list depends on cmb2 value.
My problem is, when I remove/delete the values on all combo boxes, when I click cmb2, it still shows the list of the last value chosen on cmb1 & same goes with cmb3.
What's the code to show it empty if the combo box where it's dependent to doesn't have any value?
EDIT: I think based on added information in the comment that you should look to encapsulate the logic in sub procedures and functions. To best do so, there should be some logic between named ranges and the values in the combobox.
In the below example, I created a function to handle conversions from the value in the independent combobox and the named ranges. You can supply your own connector, but I assumed that any space will be changed to an underscore (so, 'Account Information' will be replaced with 'Account_Information').
Next a subprocedure checks to confirm that the named range exists in the workbook that matches the converted value in the independent combobox. If so, the dependent box takes on that named range as its List property. If not, the dependent combobox is cleared.
The benefit to using this type of a system is that it could be repeated for other comboboxes without rewriting code. See below code and let us know if you need added help.
Private Sub UserForm_Initialize()
With Me.ComboBox1
.AddItem "Account Information"
.AddItem "Other Stuff"
End With
End Sub
Private Sub ComboBox1_Change()
With Me
LoadDependentCBO Me.ComboBox1, Me.ComboBox2
End With
End Sub
Private Function ConvertValueToNamedRange(sValue As String, sConnector As String) As String
'This function takes values in the combobox and converts them to named ranges
'The spaces are replaced with whichever connector is supplied to the function
'NOTE: I created a separate function even though this only uses a built-in function
'in case more implementation code is needed
ConvertValueToNamedRange = Replace(sValue, " ", sConnector)
End Function
Private Sub LoadDependentCBO(cboIndependent As ComboBox, cboDependent As ComboBox)
'This code looks to see if there is a match between the value of the independent combobox
'and a named range in the workbook. If not, the dependent combobox is set to be empty
Dim sTemp As String
Dim rNamedRange As Range
sTemp = ""
On Error Resume Next
sTemp = Names.Item(ConvertValueToNamedRange(cboIndependent.Value, "_")).Name
On Error GoTo 0
If sTemp = "" Then
'There is no matching named range so clear the dependent combobox
cboDependent.Clear
Else
cboDependent.List = Range(sTemp).Value
End If
End Sub
OLD POST:
The code ComboBox1.ListIndex = -1 will set the combo box to empty (change the name of the box to suit). The logic to do so depends on more details. Let us know if you need help with implementation.
I am trying to create a piece of vba code which will generate a message to the user when a user selects a value from a dropdown list/validation list in excel.
So far my script does this fine. However, I want the user to be able to select their first value from the dropdown list without getting a message, and then on the second, third or fourth time etc, if they should change their selection in the dropdown list I want the message to display.
Can someone please show me a way of doing this? Thanks in advance
'Check number of times a user has changed their selection
Dim rM As Range
Set rM = Range("M" & ActiveCell.Row).Cells.SpecialCells(xlCellTypeAllValidation)
If Intersect(Target, rM) Is Nothing Then
Else
MsgBox "changed"
End If
Add ..
Private BooRangeSelected as Boolean
... at the very top of the VBA code.
Set this value to False in the Initialize event.
Set this value to True when the dropdown list is updated.
If the value is already True when the dropdown list is selected then issue the message.
I'm assuming this macro is attached to a Workbook rather than a Form stored in "personal.xlsb". In Excel / view code double click the "ThisWorkbook" icon (see below
Private Sub Workbook_open()
Private BooRangeSelected as Boolean
BooRangeSelected = False
End Sub
This sets the variable to False once the Worksheet is opened. You can then set this to True once the dropdown has been selected
BooRangeSelected = True
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