Number only text box not working on one of two text boxes in a userform - vba

I have two text boxes on a userform that I would like to be numeric only. The first one works fine based on this( Link), however the second one, which I have implemented in exactly the same way as the first is not working, and I don't know why. Any idea why?
The first textbox is call TextBoxMainVal
The second is called perHour
Code:
'If the Main Value box does not recieve a number send a message to make them change it
Private Sub TextBoxMainVal_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBoxMainVal.Value = "" Then
ElseIf Not IsNumeric(TextBoxMainVal.Value) Then
MsgBox "Enter numbers only"
Cancel = True
TextBoxMainVal.Value = vbNullString
End If
End Sub
'I DONT KNOW WHY THIS ONE ISNT WORKING!
Private Sub perHour_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If perHour.Value = "" Then
ElseIf Not IsNumeric(perHour.Value) Then
MsgBox "Enter numbers only"
Cancel = True
perHour.Value = vbNullString
End If
End Sub
I thought there could be a naming error conflict, so I changed the textbox name, but that did not resolve it.
I cant understand why it is not working. What am I overlooking?

For those who are interested why this may happen there is an answer here. The reason, it appears, the textbox exit handler is not occurring is because it is outside of a frame. For the exit handler to work you need to stay inside the frame.

Related

Cannot validate activex textboxes in form (not a userform) just a form in the Word document itself

I've looked all over for the solution to this, finally figured I would just ask.
I have a form I've created in Word. It is not a formal "userform1" type form as in a VB project. It is written all in the Word document itself.
I am going to have a lead person email my this report every evening. I have been able to successfully have the user click the submit button and email the form (MS Word (NighlyReport.DOCM)).
In the final stages now, I am "trying with no success" to validate all of my textboxes with no luck.
I want to make each textbox required and if the user does not enter a value, I would like the "setFocus" to return the user back to the textbox. Since I am not using an official "userform" I do not seem to have this method available to me - to return the user back to the form. I have tried
_Change
_GotFocus
_LostFocus
_KeyPress
_MouseDown
All of these work fine as long as I am inside the textbox. None of them sends the user back to it.
Does anybody know a way to do this. I wanted a straightforward nice looking form to fill out and attach to outlook (which I've done). Just need to validate the textboxes. I would be willing to validate all of them with a commandbutton as well, but still cannot get the focus back to the textbox that was not filled out by the user.
For the sake of simplicity, I am posting just two textboxes here and my basic validation that is not working. To be clear, I am not using the userform grid, maybe that makes all of this impossible to do.
Thanks ahead:
Private Sub txt1_Change()
If txt1.Value = "" Then
MsgBox "need your input"
Else
Exit Sub
End If
End Sub
Private Sub txt2_Change()
If txt2.Value = "" Then
MsgBox "need your input"
Else
Exit Sub
End If
End Sub
Try something along the lines of:
Dim iShp As InlineShape, StrOut As String
For Each iShp In ActiveDocument.InlineShapes
With iShp
If .Type = wdInlineShapeOLEControlObject Then
If .OLEFormat.ClassType Like "Forms.TextBox.*" Then
If Trim(.OLEFormat.Object) = "" Then StrOut = StrOut & vbCr & .OLEFormat.Object.Name
End If
End If
End With
Next
If StrOut <> "" Then
MsgBox "The following controls have not been completed: " & StrOut
Exit Sub
End If

What property will return the caret (or cursor type bar) to the designated textbox in VBA Excel UserForms? [duplicate]

I have a textbox on a userform. If the user fails to enter anything in this textbox, I need to trap that to force an entry. I can do this easily enough, but after notifying the user tht they need to make an entry, I want the focus to return to the textbox. Right now, it doesn't do that. Here is my code:
Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 13:
If Me.txtAnswer.Value = "" Then
temp = MsgBox("You need to enter an answer!", vbCritical + vbOKOnly, "No Answer Found!")
Me.txtAnswer.SetFocus
Else
recordAnswer
End If
End Select
End Sub
This code works fine in that the message box pops up if the textbox is left blank. After clearing the message box, if I hit enter immediately again, the message box reappears, suggesting that the focus is on the textbox. However, if I try to enter a character (like the number '1' for example) nothing appears in the textbox.
Can anybody suggest how I can get the focus back on this textbox in a way that will allow the user to enter data? Thank you!
Why are you not using an 'ok' button to complete the action?
You should not bother users with messages while they are typing in a form. Do it at the end.
Private Sub OK_Click()
'// Validate form
If txtAnswer.Text = vbNullString Then
MsgBox "You need to enter an answer!", vbExclamation, "No Answer Found!"
txtAnswer.SetFocus
Exit Sub
End If
'// You have reached here so form is correct carry on
recordAnswer
End Sub
If you really want to use the behaviour you asked for then try this:
Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 13:
If Me.txtAnswer.Value = "" Then
temp = MsgBox("You need to enter an answer!", vbCritical + vbOKOnly, "No Answer Found!")
KeyCode = 0
Else
recordAnswer
End If
End Select
End Sub
The problem is that in your code you are setting focus but the enter key is firing afterwards. You don't need to set focus because the textbox already has the focus you just need to cancel the enter key.
The other answers seem really complicated. I had a similar problem and really wanted a text warning. It seemed easier for me to just make an invisible label on the form that would show up if the input was incorrect. I also made the background of the label red so that the user would notice something was wrong. Doing it this way kept the cursor visible and right where they left off.
Public Function amount(ByRef cont As MSForms.TextBox) As Integer
'makes sure that a number is used
'could change to account for decimals if necessary
Dim i As Long
On Error Resume Next
i = 0
If (cont.Value = "") Then Exit Function
Do While i < 1000000
If (cont.Value = i) Then
UserForm1.Label257.Visible = False
Exit Function
End If
i = i + 1
Loop
UserForm1.Label257.Visible = True
amount = 1
End Function
Public Sub qty_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If amount(UserForm1.qty) = 1 Then
Cancel = True
End If
End Sub
I hope this helps other who run into this problem later on.
Looking at the above code, I assume the i counter is to keep it going? Sorry a bit rusty, been a few years since I've done code.
At any rate, if thats the case you could always run it while i=0, do (or while true).
Sorry, first time posting here, hope that made sense.

TabIndex is working incorrectly

The Goal:
When I switch pages in my VBA userform, I would like a certain field to be the first input value. And then I want them to switch sequentially when I tab through them.
What I have done so far:
The pages are created (for the most part, they still need an artistic mind to make it look like an engineer didn't do it), the logic is made, basically everything is done. The input fields tabIndex propertys are set starting at 20 and going up to 27 in the order I want them in. Pictures will be attached below.
The Problem:
When I push the next button, the userform automatically goes to the "Cooling system" drop down. If I push tab, it goes to the next dropdown. Then through the other options in a strange but constant order. And the weird thing is, I can type but no text appears. The cursor moves, but nothing comes behind it. After I have tabbed through everything, if I push tab again only THEN does it do what I want it to do. I have attached pictures and the code for the next button. Thanks for your help in advanced. Let me know if I can clarify anything!
The Page that works fine:
The problem page (I tried to show how nothing shows when you type and it goes to that drop down automatically):
Code for "Next" button:
Private Sub bNextSystem1_Click() 'checks to see if all parameters are entered
If IsNumeric(Me.txtS1elec.value) = True And IsNumeric(Me.txtS1NG.value) = True And IsNumeric(Me.txtS1sqft.value) = True Then
If Me.txtS1elec.value <> "" And Me.txtS1NG.value <> "" And Me.txtS1sqft.value <> "" And Me.ddS1Cooling.ListIndex > -1 And Me.ddS1Heating.ListIndex > -1 Then
NextPage
Me.txtS1elec.BackColor = vbWhite
Me.txtS1NG.BackColor = vbWhite
Me.txtS1sqft.BackColor = vbWhite
Else
MsgBox "Please check to see if all options are selected or entered."
GoTo CleanFail
End If
Else
HighlightBadCells1 'checks for incorrect cell input values
MsgBox "Please check the highlighted cells"
GoTo CleanFail
End If
Me.txtS2elec.value = Me.txtS1elec.value
Me.txtS2NG.value = Me.txtS1NG.value
CleanFail:
End Sub
Code for "NextPage" Sub routine:
Private Sub NextPage()
MultiPage1.Pages(MultiPage1.value + 1).Visible = True 'hides current page
MultiPage1.Pages(MultiPage1.value).Visible = False 'reveals next page
End Sub
Select the Multipage Page
CLick View -> Tab Oder
This will show the Tab Order Dialog.

VBA Nested IF statement

I want to show a message box when a specific cell has a particular value in it. I have done this with the following code;
If Range("P8") = "Y" Then
MsgBox "Message here"
End If
This is within the Worksheet_Change sub so shows the message box everytime another cell value changes. I have tried to get around this by adding a boolean variable, set to true when the messagebox has been shown the first time;
If Range("P8") = "Y" Then
If messageshown = False Then
messageshown = True
MsgBox "Message here"
Else
End If
Else
End If
However the message box still shows every time I change a cell in the worksheet. I have a feeling it';s to do with the way I have written the nested if statement but have tried various different ways and orders of where I place else and end if but to no avail.
Use the Target argument instead - this refers to the actual cell being changed, which is what you are interested in. Test the address of the Target to see if it's the cell you need and then act accordingly. This will stop the message showing when another cell is changed.
Private Sub Worksheet_Change(ByVal Target As Range)
With Target
If .Address = "$P$8" And .Value = "Y" Then MsgBox "Message here"
End With
End Sub
Try this code, it first checks which cell is changed, if it is anything but P8, it will not pop the messagebox.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$P$8" Then
If Range("P8") = "Y" Then
MsgBox "This works"
End If
End If
End Sub
As pointed out by Macro Man, there is a more optimal, more efficient option.

Excel VBA Userform QueryClose: Cancel not working

I've written the code below so that it will check if a process has been completed or not before closing the form. This userform is used as a scoresheet that will make range("A6") green to signify a pass, or range("B6") red to signify a fail as the final step of the sub, before unloading the form.
From what I've checked online so far, it should be working. While debugging, the macro gets all the way to where it says Cancel = True, reads over the line, but the form closes anyway.
Why isn't the cancel registering even when it reads over the line?
Private Sub Userform_queryclose(CloseMode As Integer, Cancel As Integer)
Dim wbScoreCard As Workbook
Dim wsScoreCard As Worksheet
Dim MSG As String
Set wbScoreCard = Workbooks(NameBox.Value)
Set wsScoreCard = wbScoreCard.Worksheets(Format(Date, "MM.dd.yy") & " " & CallType.Caption)
If Err.Number = 0 Then
If wsScoreCard.Range("A6").Interior.Color <> vbGreen Then
If wsScoreCard.Range("B6").Interior.Color <> vbRed Then
Beep
MSG = MsgBox("This scorecard is not complete! If you close it now, this scorecard will not be saved. Continue?", vbYesNo, "Warning - Scorecard Incomplete")
If MSG = vbYes Then
wbScoreCard.Close savechanges:=False
Exit Sub
Else
Cancel = True
Exit Sub
End If
End If
End If
End If
End Sub
Couple of things:
You're not shutting off error handling, so the Err.Number = 0 check has no effect; if there's a runtime error, execution jumps straight out of the procedure anyway.
MSG should be a vbMsgBoxResult, not a String. Your code only works because of implicit type conversions from the underlying Integer value to the String type you're forcing it into.
Unless you didn't post your entire code, Exit Sub is redundant in both branches.
The problem can be reproduced with simpler code:
Private Sub Userform_queryclose(CloseMode As Integer, Cancel As Integer)
Cancel = True
End Sub
The problem is that you made up that signature or somehow typed it up from memory. This is the signature for the QueryClose handler:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Notice the ordering of parameters.
You'll get the expected behavior by setting your CloseMode to True instead of Cancel... but a better fix would be to put the parameters in the correct order.
Event handlers don't really care about parameter names: it's about types and order. Since both parameters are Integer, it's down to ordering: the first Integer parameter is interpreted as the Cancel parameter, and the second is the CloseMode - the form / COM doesn't care how you called them, it's going to read the Cancel value from the first parameter anyway.
You can avoid this problem in the future, by selecting the event from the dropdowns at the top of the code pane:
Make sure the left-hand dropdown says "UserForm", and then select "QueryClose" from the right-hand dropdown:
If there's no handler for it, the VBE will create one properly formed for you.