Auto scroll sheet to active row while using userform - excel

Entering data via a userform. After a few entries I can no longer see the active cell and I can't scroll the sheet while the userform is active. I would like to have the sheet auto-scroll to keep the active cell/row visible while I enter data on the userform.
I've tried adding some code I found online but they've all failed to get the result I'm looking for.
Private Sub Label1_Click()
End Sub
Private Sub Label2_Click()
End Sub
Private Sub TextBox1_Change()
End Sub
Private Sub TextBox2_AfterUpdate()
Dim emptyRow As Long
If TextBox1.Value <> "" And TextBox2.Value <> "" Then
With ThisWorkbook.Sheets("RO-BOX DETAILS")
emptyRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
.Cells(emptyRow, 1).Value = TextBox1.Value
.Cells(emptyRow, 2).Value = TextBox2.Value
TextBox1.Value = ""
TextBox2.Value = ""
TextBox1.SetFocus
End With
End If
End Sub
Private Sub UserForm_Click()
End Sub
I'm not experienced with VBA. I honestly thought there would be a simple code snippet I could add in, but so far, no joy.
I scan into textbox 1 and it moves the focus to textbox 2
I scan into textbox 2 and it adds the data to the next empty row - no
clicking 'OK' required.
The focus returns to textbox 1.
Repeat
Now I just want it to keep the next empty row visible so I can see the entries go in on the fly. Basically to ensure they scanned correctly. Right now, I have to close the userform every so often and scroll down and look manually. PITA. :)

It won't quite achieve the autoscrolling you requested, but you could try calling the userform with it's ShowModal property set to "modeless". That would at least allow the user to manually scroll the sheet.
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/showmodal-property
...there's no example to follow on that page, but it would go something like...
sub CallNormsUserForm()
NormsUserForm.show vbModeless
end sub

Related

How to add a label and textbox based on combo box selection on a userform in excel

I am currently working on a userform to create an order for users at a company to send to my dept.
At the moment i have come to a standstill as i am struggling to work out the following.
I have a combobox which has a list of products our business offers. Based on the selection i want to be able to add labels and textbox which require the user to enter data for example.
If this selection in the combo box then
Enter name, date required, location of user etc.
Also this needs to be specific to the combobox selection.
Any help would be much appreciated :)
UPDATE
Apologies, as i did not have any code for that function I did not add any Here is the code i have.
Private Sub CommandButton1_Click()
Windows("RFS User Form Mock.xlsm").Visible = True
End Sub
Private Sub LegendDefinition_Change()
LegendDefinition.Locked = True
End Sub
Private Sub RequestList_Change()
Dim i As Long, LastRow As Long
LastRow = Sheets("Definition").Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Sheets("Definition").Cells(i, "A").Value = (Me.RequestList) Then
Me.DefinitionBox = Sheets("Definition").Cells(i, "B").Value
End If
Next
End Sub
Private Sub RequestList_DropButtonClick()
Dim i As Long, LastRow As Long
LastRow = Sheets("Definition").Range("A" & Rows.Count).End(xlUp).Row
If Me.RequestList.ListCount = 0 Then
For i = 2 To LastRow
Me.RequestList.AddItem Sheets("Definition").Cells(i, "A").Value
Next i
End If
End Sub
Sub UserForm_Initialize()
SiteList.List = Array("Birmingham", "Bristol", "Cardiff", "Chelmsford", "Edinburgh", "Fenchurch Street", "Glasgow", "Guernsey", "Halifax", "Homeworker", "Horsham", "Ipswich", "Jersey", "Leeds", "Leicester", "Lennox Wood", "Liverpool", "Manchester", "Peterborough", "Redhill", "Sunderland", "Madrid")
End Sub
Private Sub VLookUp_Change()
VLookUp.Locked = True
End Sub
When posting a question, you are expected to provide some code showing where you're standing trying to address the problem. Here's nevertheless a short demo that will give you a starting point.
Create a new UserForm and put a combobox, a label and a textbox on it; ensure they're named ComboBox1, Label1 and TextBox1, respectively.
Then, paste this code in the form's module:
Option Explicit
Private Sub ComboBox1_Change()
Dim bVisible As Boolean
'Only show the label and the textbox when the combo list index is 1, which corresponds to "Item 2".
'Note: bVisible = (ComboBox1.Text = "Item 2") would also work.
bVisible = (ComboBox1.ListIndex = 1)
Label1.Visible = bVisible
TextBox1.Visible = bVisible
End Sub
Private Sub UserForm_Layout()
'Populate the combo.
ComboBox1.AddItem "Item 1", 0
ComboBox1.AddItem "Item 2", 1
'Note: the code below could be removed by setting the corresponding
'design-time properties from the form designer.
ComboBox1.Style = fmStyleDropDownList
Label1.Visible = False
TextBox1.Visible = False
End Sub
Then press F5 to show the form. You'll notice that the label and textbox are only visible when the combo shows "Item 2". The visibility adjustment is performed within the ComboBox1_Change event handler.
If you plan on having numerous controls shown / hidden depending on your combo's value, you could group them into one or more Frame controls, and show / hide those frames instead.

Double Click Event on the items of the ListBox of a Userform VBA

I am trying to do a small "save as" interface on excel using vba, so that I can save some of the information that i have putted in my sheet in another sheet. I am almost done with it and it looks like this: click here to see my Save As interface
My problem is that I want to put an event on double clicking on one of the elements of my list, let's say SoCs2. On double click, I want the string "SoCs2" to appear in the textbox below.
I tried something like that:
Private Sub Listbox1_BeforeDoubleClick(ByVal Cancel As MSForms.ReturnBoolean)
With Me.ListBox1
For i = 0 To .ListCount - 1
If .Selected(i) Then
Me.TextBox1.Value = .List(i, 0)
Exit For
End If
Next
End With
End Sub
My ListBox is called ListBox1 and my TextBox is called TextBox1.
Unfortunately, this code doesn't work: when I double click on one of the items of my ListBox, it does absolutely nothing.
Can somebody help me with this issue ?
The name of the Event Handler you are looking for is Listbox1_DblClick. Try this:
Private Sub Listbox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
With Me.ListBox1
For i = 0 To .ListCount - 1
If .Selected(i) Then
Me.TextBox1.Value = .List(i, 0)
Exit For
End If
Next
End With
End Sub

Using VBA userform to select ranges on multiple sheets - sheet changes back to original activesheet

I have a userform which has multiple RefEdit controls. I need the user to select ranges from multiple sheets and the userform has to be complete before the rest of the code can run.
Issue: The activesheet is "Sheet1" when the userform is initiated. Each time I select a range on "Sheet2" and click into the next RefEdit the visible Excel sheet returns to "Sheet1". I'd like the sheet to remain on "Sheet2", since clicking between the sheets significantly increases the time it takes to select the data.
Because I need the userform to be completed before continuing with my code, using "vbModeless" doesn't appear to work.
I've tried to step through the userform events which appeared to be relevant but none were activated when I entered the RefEdit, selected the data, or left the RefEdit.
Thanks in advance for any help!
Edit: Using some input from the responses and doing some more research I think I've figured out the problem and a work around.
RefEdit events such as Change or Exit (I tried all of them I think) don't appear to trigger when a change occurs in the control. So I couldn't write code to manipulate the activesheet when I changed the control. A workaround found here: http://peltiertech.com/refedit-control-alternative/ uses a textbox and inputbox to simulate a RefEdit control and will actually trigger when changes are made! Code is below. To add other "RefEdit" controls you should repeat the code in the Userform_Initialize event for each control, then add another TextBox1_DropButtonClick and update TextBox1 to the name of the new control. In use when the control updates the workbook jumps to the previous activesheet and then returns the desired activesheet. Not as smooth as I'd like but much better than it was.
Code:
Private Sub CancelButton_Click()
Unload Me
End
End Sub
Private Sub OKButton_Click()
UserForm1.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
End
End Sub
Private Sub UserForm_Initialize()
Me.TextBox1.DropButtonStyle = fmDropButtonStyleReduce
Me.TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
End Sub
Private Sub TextBox1_DropButtonClick()
Dim ASheet As String ' Active sheet
Me.Hide
'Use input box to allow user to select a range
On Error Resume Next
Me.TextBox1.Value = Application.InputBox("Select the range containing your data", _
"Select Chart Data", Me.TextBox1.Text, Me.Left + 2, _
Me.Top - 86, , , 0)
On Error GoTo 0
'Check if there is a sheet name - if the range selected is on the activesheet the output of the inputbox doesn't have a sheet name.
If InStr(1, Me.TextBox1.Value, "!", vbTextCompare) > 0 Then ' there is a sheet name
ASheet = Replace(Split(Me.TextBox1.Value, "!")(0), "=", "") ' extract sheet name
Else ' there is no sheet name
Me.TextBox1.Value = "=" & ActiveSheet.Name & "!" & Replace(Me.TextBox1.Value, "=", "") ' add active sheet name to inputbox output
ASheet = ActiveSheet.Name
End If
Worksheets(ASheet).Activate ' set the active sheet
Me.Show
End Sub
Have you tried something as simple as:
Sheets("Sheet2").Select
somewhere in the beginning of your form code ?
Since you haven't posted your code, it's hard to provide a good answer.
Hope this helps a little :)
This form module worked for me.
Private Sub CommandButton1_Click() 'Cancel Button
Unload Me
End Sub
Private Sub CommandButton2_Click() 'GO Button
Dim newSheet As Worksheet
abc = Split(RefEdit1.Value, "!")
cbn = abc(0)
Unload Me
Set newSheet = Worksheets(abc(0))
newSheet.Activate
End Sub

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!

Excel Userform Textbox Behavior

I have a textbox on a userform. It is the only textbox on the form. There are three labels and two buttons in addition to this textbox. Basically, I want the focus to remain on this textbox under all scenarios, other than the moment that one of the buttons would be clicked, but then I want the focus to come right back to the text box. Both buttons have "TakeFocusOnClick" and "TabStop" set to False. I was having problems with getting the focus set to the textbox, which is why I changed these two settings.
Once I changed these settings, the Enter key in the textbox stopped having any effect. I have events written for _AfterUpdate and _KeyPress for the textbox, but they don't fire. As you can see in the code, I have commented out the lines to set the focus to this textbox. Since it is now the only object that can take focus, these lines are not needed (theoretically). When I allowed the other objects to take focus, these lines weren't having any effect (focus was switching to the buttons despite these SetFocus lines).
Here is the code. It is very simple, except that the Enter key isn't triggering the event. Can anyone see why? Thanks.
Private Sub btnDone_Click()
Application.Calculation = xlCalculationAutomatic
formMath.Hide
'Clear statistics
Range("attempts").Value = 0
Range("correct").Value = 0
Sheet5.Range("A2:W500").ClearContents
End Sub
Private Sub btnSubmit_Click()
recordAnswer
'formMath.txtAnswer.SetFocus
End Sub
Private Sub txtAnswer_AfterUpdate()
recordAnswer
'formMath.txtAnswer.SetFocus
End Sub
Private Sub txtAnswer_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii = 13 Then
recordAnswer
End If
End Sub
Private Sub UserForm_Initialize()
'Initialize manual calculation
Application.Calculation = xlCalculationManual
Application.Calculate
'Initialize statistics
Range("attempts").Value = 0
Range("correct").Value = 0
Sheet5.Range("A2:W500").ClearContents
'Initialize first problem
newProblem
End Sub
Sub recordAnswer()
'Update statistics
Dim attempts, correct As Integer
attempts = Range("attempts").Value
correct = Range("correct").Value
Range("results").Offset(attempts, 0).Value = attempts + 1
Range("results").Offset(attempts, 1).Value = lblTopNum.Caption
Range("results").Offset(attempts, 2).Value = lblBotNum.Caption
Range("results").Offset(attempts, 3).Value = lblBop.Caption
Range("results").Offset(attempts, 4).Value = Range("Answer").Value
Range("results").Offset(attempts, 5).Value = txtAnswer.Text
If (Range("Answer").Value = txtAnswer.Text) Then
Range("results").Offset(attempts, 6).Value = 1
Else
Range("results").Offset(attempts, 6).Value = 0
End If
'Update attempts and success
Range("attempts").Value = attempts + 1
Range("correct").Value = correct + 1
newProblem
End Sub
Sub newProblem()
Application.Calculate
formMath.lblTopNum.Caption = Range("TopNum").Value
formMath.lblBotNum.Caption = Range("BotNum").Value
formMath.lblBop.Caption = Range("ProbType").Value
formMath.txtAnswer.Value = ""
'formMath.txtAnswer.SetFocus
End Sub
To start off
You can either in the design mode, set the TabIndex property of the Textbox to 0 or you can set the focus on the textbox in the UserForm_Initialize()
Private Sub UserForm_Initialize()
TextBox1.SetFocus
End Sub
Similarly after any operation that you perform, simply call the TextBox1.SetFocus to revert to the textbox.
Option Explicit
Private Sub UserForm_Initialize()
TextBox1.SetFocus
End Sub
Private Sub CommandButton1_Click()
MsgBox "Hello from Button 1"
TextBox1.SetFocus
End Sub
Private Sub CommandButton2_Click()
MsgBox "Hello from Button 2"
TextBox1.SetFocus
End Sub
Let me know if this is not what you want?
I found a way to accomplish this. In the code above I took out the _KeyPress and _AfterUpdate events and replaced them with:
Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 13: recordAnswer
End Select
End Sub
Not sure why the other methods didn't work, but this does.
Also not sure why simply setting the focus directly didn't work. I suspect that the focus was being set, but then something else was happening subsequently that was changing the focus off of the textbox. Just a guess.
Thanks for the help. I appreciate it.

Resources