I am writing an If statement to test if I i have an option selected in two combo boxes. The combo box being checked is generated from array with two values. One of those cells are blank so the top value is blank in the combo box.
My if statement is
The array is
Private Sub cbApplicationSelection_Change()
If (eMassWelcome.cbwesitechoose.text = "") Then
eMassWelcome.cbApplicationSelection.text = ""
MsgBox "A website has not been selected. Please select a website from the dropdown and try again."
End If
Exit Sub
End Sub
This works.
The problem is the pop up comes up 3 times and im not sure why. I've tried IsNull() and listindex = -1. IsNull() did not work and list index gave me the same result as above. All this is being done with vba in excel.
Have you placed any change event for cbApplicationSelection? If so, as you are changing it's value, the change event will also get triggered.
Private Sub cbApplicationSelection_Change()
If eMassWelcome.cbwesitechoose.text = "" Then
MsgBox "A website has not been selected. Please select a website from the dropdown and try again."
End If
Exit Sub
End Sub
Related
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.
Alright, so here’s the code for my UserForm:
Private Sub CancelButton_Click()
Unload Me
End Sub
Private Sub ClearButton_Click()
Call InventoryEntryBox_Initialize
End Sub
Private Sub SubmitButton_Click()
Dim emptyRow As Long
'Make Inventory Test sheet active
Worksheets("InventoryTest").Activate
'Transfer Information
Worksheets("InventoryTest").Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).Value = PartNumberComboBox.List
Worksheets("InventoryTest").Cells(Rows.Count, "C").End(xlUp).Offset(1, 0).Value = LocationTextBox.Value
Worksheets("InventoryTest").Cells(Rows.Count, "D").End(xlUp).Offset(1, 0).Value = QuantityTextBox.Value
Worksheets("InventoryTest").Cells(Rows.Count, "F").End(xlUp).Offset(1, 0).Value = CommentsTextBox.Value
Call InventoryEntryBox_Initialize
End Sub
Private Sub InventoryEntryBox_Initialize()
'Fill PartNumberComboBox
PartNumberComboBox.List = ActiveWorkbook.Sheets("Test2").Range("B2:B43").Value
'Empty Location Text Box
LocationTextBox.Value = ""
'Empty Quantity Text Box
QuantityTextBox.Value = ""
'Empty Comments Text Box
CommentsTextBox.Value = ""
'Unit Of Measure auto-fill box
'Description auto-fill box
DescriptionFormula.Value = Application.WorksheetFunction.VLookup(PartNumberComboBox.List, ActiveWorkbook.Sheets("Test2").Range("B2:D43"), 3, False)
'Set focus on Empty Part Number text box
PartNumberTextBox.SetFocus
End Sub
Now, the idea with this code is to have User Form so someone can fill it out (the PartNumberComboBox, LocationTextBox, QuantityTextBox, and CommentsTextBox) in order to catalogue inventory on what items are in what places and in what quantity. When someone fills out an item number in the PartNumberComboBox, the DescriptionFormula will auto-fill with data from a list (Noted as PartDescription, which includes D2:D43 in the sheet Test2).
My problem, however, is two-fold: The DescriptionFormula.Value box does not auto-fill with data when someone enters in a part number in the PartNumberComboBox, and when I try to hit the “submit” button to confirm the data entered in the form and put it in the areas specified in the code, I get a dialogue box that pops up and says “Run-time error 70: Permission Denied”, then the "PartNumberComboBox.List = ActiveWorkbook.Sheets("Test2").Range("B2:B43").Value" is highlighted when I go to debug.
I’m not sure if it’s a problem with my code, or if it’s a limitation of Excel or Vlookup based on what I’m doing… or if it’s something else. Any kind of help anyone could offer would be a blessing at this point.
I've actually solved my own question:
So it turns out that I needed to write a new sub for this particular equation, not embed it in my Initialize sub. Here's what I wrote to get it to work:
Private Sub PartNumberComboBox_Change()
Me.UnitOfMeasureFormula.Value = Application.WorksheetFunction.VLookup(Me.PartNumberComboBox.Value, Sheets("sheet2").Range("a2:c43"), 3, False)
Me.DescriptionFormula.Value = Application.WorksheetFunction.VLookup(Me.PartNumberComboBox.Value, Sheets("sheet2").Range("a2:c43"), 2, False)
End Sub
while changing my "Description auto-fill box" to this:
'Empty Description label
DescriptionFormula.Value = ""
What this does is empty out the box that the auto-fill will go in on startup of the Userform, then using a _Change sub with the ComboBox that the formula is referencing so it alters the DescriptionForumula based on what the ComboBox says with a simple VLookup formula. Now it's working smoothly and I'm back on track!
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
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)
I set up a excel sheet with drop-down menus for some of the cells. The
user can only select values from that list and an error message pops up
when something is typed it that is not in the list (via Data Validation
Error Alert).
So this works all fine ... But when the user copy paste into the cells then validation doesnt work. How to make validation effective in case of copy paste.
I have searched and found one solution but its not working.
Here is the code that I have found. but its not working any more..It always return true enven I copy paste worng
Private Sub Worksheet_Change(ByVal Target As Range)
If HasValidation(Range(ActiveCell.Address)) Then
Exit Sub
Else
Application.Undo
MsgBox "Your last operation was canceled." & _
"It would have deleted data validation rules.", vbCritical
End If
End Sub
Private Function HasValidation(r) As Boolean
On Error Resume Next
x = r.Validation.Type
If Err.Number = 0 Then HasValidation = True Else HasValidation = False
End Function
It looks like you took the code from this page:
http://www.j-walk.com/ss/excel/tips/tip98.htm
When Worksheet_Change fires, your code always refers to the active cell, not the target where the copy/paste operation is being performed.
Change
ActiveCell.Address
to
Target.Address
and see if that works.
The "Target.Address" worked for me as mentioned by #JimmyPena.
But the solution still brings a bug, that if one tries to add another validation after adding the above mentioned VB code, the user is fired with the amount of message boxes produced by the vb code which is applied to the number of cells (viz. You will have to click on "OK" of the message box provided by the VB code for the number of cells the VB code has been applied to.. If code applied to 40 cells then you have to click "OK" 40 times... phew..)
Can you please try to help to add another condition to help this?
Or the last way that remains to only add the VB code after adding all the validations.