set value for other userform controls on userform close - excel

really struggling with this one, found a solution for the time being but it's not really a satisfactory one.
I have a workbook with two user forms, one to input data and one to search for previously entered data and a third user form designed as a date picker form which is set to activate on entry of a designated date text box.
Individually I have no problem, the user clicks the text box and the date picker form appears, they make their selection which closes the date picker form and adds the date to the text box. On the "input data" form I have a multi page with a single date selection text box on each of the two pages, on the "find data" form I have an option to search a single date or a range, 3 date selection text boxes in total.
now I am noticing that userform1 (input data) is prompting a run time error 91 - object variable or With block variable not set and is flagging the first line for userform2 in the code whenever I select a date from the date picker form.
what I did notice however was that the correct date was still being entered into the textbox so as a fix I added an 'On error goto' line above the highlighted line which is allowing the action to take place without interruption. What I did notice was that now if I enter a date anywhere on userform2 (find data) and then close the form and decide I want to enter data instead, the text box on userform1 will contain whatever the previous selection was on userform2. What is especially puzzlng about this to me is that the initialize event for UF1 enters the current date in the date text box.
see code below, is there a much better way to write this? I hope I explained well enough, please let me know if I can provide additional details to help.
Sub CloseDatePicker(save As Boolean)
If UserForm1.MultiPage1.Value = 0 Then
UserForm1.tbDate.Text = Calendar1.Value
UserForm1.cbMember.SetFocus
ElseIf UserForm1.MultiPage1.Value = 1 Then
UserForm1.tbDate2.Text = Calendar1.Value
UserForm1.cbMember2.SetFocus
End If
On Error GoTo dpexit
If UserForm2.ActiveControl.Name = "TextBox1" Then
UserForm2.TextBox1.Text = Calendar1.Value
End If
If UserForm2.ActiveControl.Name = "TextBox2" Then
UserForm2.TextBox2.Text = Calendar1.Value
ElseIf UserForm2.ActiveControl.Name = "TextBox3" Then
UserForm2.TextBox3.Text = Calendar1.Value
End If
dpexit:
Me.Hide
End Sub

Right out the gate, the first problem I see with your code is you're trying to change the value of a text box with the .Text property. I've personally never had luck with using .Text to set value as it consitently throws Err:91. Instead I've found it's better to use .Value.
Sub CloseDatePicker(save As Boolean)
If UserForm1.MultiPage1.Value = 0 Then
UserForm1.tbDate.Value = Calendar1.Value
UserForm1.cbMember.SetFocus
ElseIf UserForm1.MultiPage1.Value = 1 Then
UserForm1.tbDate2.Value = Calendar1.Value
UserForm1.cbMember2.SetFocus
End If
' On Error GoTo dpexit 'disabled this for you to test your code
If UserForm2.ActiveControl.Name = "TextBox1" Then
UserForm2.TextBox1.Value = Calendar1.Value
End If
If UserForm2.ActiveControl.Name = "TextBox2" Then
UserForm2.TextBox2.Value = Calendar1.Value
ElseIf UserForm2.ActiveControl.Name = "TextBox3" Then
UserForm2.TextBox3.Value = Calendar1.Value
End If
dpexit:
Me.Hide
End Sub

Related

After setting ActiveX textbox to empty value, previous text briefly appears in box before disappearing again

I created a data entry form on a spreadsheet using ActiveX TextBoxes. These are coupled with a submit details button and a clear data button. Both buttons at the end of execution set the text boxes back to blank to be refilled by the next user.
After the boxes are set to "", when the user begins filling the form each time the user selects one of the text boxes the previous entry details briefly appear in the text box then disappear.
This is a quite frustrating issue as I am trying to make it so the previous users details are hidden.
I searched many articles on the best way to set text boxes to empty and it seems that the main way is to set the .text property to "". There seems to be no mention of this behavior.
Sub clearForm()
' Worksheets("Student Data").userName.Text = ""
' Worksheets("Student Data").emailAddr.Text = ""
' Worksheets("Student Data").contactNum.Text = ""
' Worksheets("Student Data").Course.Text = ""
' Worksheets("Student Data").gradDate.Text = ""
' Worksheets("Student Data").addComment.Text = ""
textbox1clear
End Sub
Sub submitData()
'Code here that takes users entered data and outputs to hidden and protected sheet
'After data copied text boxes are cleared of users information, same as above sub
Worksheets("Student Data").userName.Text = ""
Worksheets("Student Data").emailAddr.Text = ""
Worksheets("Student Data").contactNum.Text = ""
Worksheets("Student Data").Course.Text = ""
Worksheets("Student Data").gradDate.Text = ""
Worksheets("Student Data").addComment.Text = ""
End Sub
Sub textbox1clear()
Dim sel
sel = Selection.Address
Sheet1.userName.Activate
Application.SendKeys ("Test ")
Sheet1.userName.Value = ""
Range(sel).Activate
End Sub
Expected - Text boxes should be clear of data ready for next user.
Actual - Text boxes are clear until user selects them to begin entering data at which point previous entry briefly appears in the box and disappears again.
This is common textbox behaviour. Unless the textbox is selected again, the changes aren't actually completed. I can see how this is inconvenient if used by other users and data entered is confidential. After numerous tests, the only working way I found around this is to trigger this flicker after clearing by making VBA select and deselect the input box, and simulating new user input with sendkeys.
Sub textbox1clear()
Dim sel
sel = Selection.Address
Sheet1.TextBox1.Activate
Application.Sendkeys(" ")
Sheet1.TextBox1.Value = ""
Range(sel).Activate
End Sub
I have built in a selection recall to make it (slightly) more seamless if the sub is called with a button. However if this is omitted and no selection is made after this sub is ran, the text will flicker again when the textbox is deselected.
Also note this should always be called manually, if it is called from a Textbox_LostFocus like I did, it will enter a continuous loop as long as the textbox isn't selected.
It's not a very elegant solution, but if data protection is priority, it will do the trick.
If this is not sufficient, you might want to hide your input altogether if this is an option.
you could use a quite long string made of "spaces" and then substitute them with a single "space"
Public Sub clearForm()
Worksheets("Student Data").userName.Text = " " 'vbNullString
Worksheets("Student Data").userName.Text = vbNullString
End Sub
make sure that quite long is enough for your textbox to be covered
Or
you could use a "dummy/informative" text to be removed right after entering the textbox for a subsequent input
Public Sub clearForm()
Worksheets("Student Data").userName.Text = "cleared"
…. (rest of your code
End Sub
Private Sub userName_GotFocus()
With Worksheets("Student Data").userName
If .Text = "cleared" Then .Text = vbNullString
End With
End Sub
Private Sub emailAddr_GotFocus()
With Worksheets("Student Data").emailAddr
If .Text = "cleared" Then .Text = vbNullString
End With
End Sub
… (and so on for all your textboxes)

Excel VBA - Label is blank first time running the form, later always 1 step behind

I have a userform with 1 label (lword). The label needs to be updated with a variable every time the code is being run. Every time the code is being run the activecell changes and therefore also the value.
The first time the code is being run the label is blank (I deleted the default caption in the properties). The variable which should give the value to the label is being updated and shows the correct value. I included a MsgBox to test this (MsgBox word).
When you run the form for the second time or every time thereafter it shows always the previous value. Meaning updating the label seems always one step behind.
This is the code what I have so far:
Sub Random_Words()
Dim i As Integer
Dim word As String
Dim answer As String
Dim Rng As Range
i = ActiveSheet.UsedRange.Rows.Count
Set Rng = Range("B1:B" & i)
Cells(Int((i * Rnd) + 1), 2).Select
word = ActiveCell.Value
answer = ActiveCell.Offset(0, -1).Value
MsgBox word
Load UserForm1
UserForm1.Show
UserForm1.lword.Caption = word
End Sub
I've been trying and reading several sites, but nothing worked out.
Also Userform1.Repaint doesn't help.
Thanks a lot in advance and in case you need more info, let me know.
If you set the ShowModal property to False you will see the expected behavior.
When the line UserForm1.Show executes, while the form is Modal, the next line will not execute until you close the form yourself (actually it hides the form and allows the sub to continue). You never execute Unload in your code so the form remains and the the label's value is set to the new value of word after it is "closed". The next time you show the form (not re-load, actually), the old value is showing up, etc. To verify what I just described, modify your code like this:
. . .
MsgBox "word = " & word ' the new value is assigned to "word"
Load UserForm1
UserForm1.Show ' the old value of "word" is showing
UserForm1.lword.Caption = word ' the new value is assigned to the label
MsgBox "caption = " & UserForm1.lword.Caption
End Sub

General function to color applicable comboxes

I'm running some VBA code in Excel and I made a a combo box that will turn red and set the focus on it when there is no value entered.
If cmb = "" Then
cmb.BackColor = vbRed
lbl.ForeColor = vbRed
cmb.SetFocus
Exit Sub
Else
cmb.BackColor = vbWhite
lbl.ForeColor = vbBlack
End If
As I have many combo boxes on my form, I want to build a function or procedure that I can call for any combo box that I want.
Can anyone help?
Here's a general function that you can pass a ComboBox to:
Function ValidateComboBox(c As ComboBox) As Boolean
If Len(c.Text) = 0 Then
c.BackColor = vbRed
Controls(c.Tag).ForeColor = vbRed ' Set associated label color, also
c.SetFocus
ValidateComboBox = False
Else
c.BackColor = vbWhite
Controls(c.Tag).ForeColor = vbBlack ' Set associated label color, also
ValidateComboBox = True
End If
End Function
You call it like this, for example when the form is submitted:
' [OK] clicked. Submit form...
Private Sub cmdOK_Click()
If Not ValidateComboBox(ComboBox1) Then Exit Sub
If Not ValidateComboBox(ComboBox2) Then Exit Sub
If Not ValidateComboBox(ComboBox3) Then Exit Sub
...
End Sub
The tricky part is that you have a label that corresponds to each combo box that needs to be updated as well. You can either design the function to accept both a ComboBox control and a Label control and pass both each time, or you take advantage of the combo box's Tag property, as I've done above. For each combo box, just enter the name of the corresponding Label control into its Tag property using the Properties window in the designer.
For example, if ComboBox1 has a label named Label1, then enter "Label1" (without the quotes) into ComboBox1's Tag property. The routine above will look for the label/control with that name and set its color appropriately as well.

Excel VBA UserForm Vlookup error

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!

Require selection - Excel VBA List Box

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

Resources