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

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

Related

MS Word VBA Macro from validation

I'm trying to do what, I think, ought to be the simplest of things, but I can't get it to work. i have an MS Word document with a number of legacy drop-down and text fields:
The first option in each drop-down is "Select ...", and if a user tabs out of one of the drop-downs without choosing something other than the first "Select ...", I want a msgbox to appear to tell them to make a selection, which works. What doesn't work, is that after the user dismisses the msgbox, I want the insertion point to return to the drop-down that they didn't select.
I understand that VBA has "timing issues", and from what I've read, one way to address these timing issues is to call the "return" macro from the validation macro. So I've written two macros:
Sub Validate()
' Dim strBookmark As String
' strBookmark = Selection.Bookmarks(1).Name
10: If (bool_debug) Then MsgBox ("NotSelected() - 10: strBookmark = " & strBookmark)
With ActiveDocument
If (strBookmark = "Locality") Then
Call Salary_Step
ElseIf (strBookmark = "Series") Then
20: If (bool_debug) Then MsgBox ("NotSelected() - 20: .FormFields(strBookmark).Name = " _
& .FormFields(strBookmark).Name)
If ((Len(.FormFields(strBookmark).Result) <> 4) Or (Not IsNumeric(.FormFields(strBookmark).Result))) Then _
MsgBox ("Please enter a 4 digit number.")
Call GoBackToPrevious(.FormFields(strBookmark).Name)
ElseIf (.FormFields(strBookmark).DropDown.Value = 1) Then
MsgBox ("Please select a " & Replace(Selection.FormFields(strBookmark).Name, "_", " ") & ".")
Call GoBackToPrevious(.FormFields(strBookmark).Name)
End If
End With
End Sub
and
Sub GoBackToPrevious(strPreviousField)
10: If (bool_debug) Then MsgBox ("GoBacktoPrevious - 10: strPreviousField = " & strPreviousField)
ActiveDocument.Bookmarks(strPreviousField).Range.Fields(1).Result.Select
End Sub
But when I tab out of any of the form fields, the insertion point jumps to the next form field and not back to the one that I just tabbed out of.
I know from the debug code that GoBackToPrevious is being passed the name of the current form field, but MS Word advances to the next field regardless.
I'd really appreciate it if someone can tell me how make MS Word return to and select the drop-down the user did not select appropriately instead of jumping to and selecting the next form field in the document.
Thank you.
P James Norris
EDIT:
Based on #TimothyRylatt comments, I have modified my macro and when they're called.
I have edited Validate as above (commenting out the Dim the strBookmark assignment, and I call it "on entry" to the next form field.
strBookmark is Dimed on the module's declaration section:
Option Explicit
Const bool_debug As Boolean = True
Const str_password As String = "###" ' I have a different password
Public strBookmark As String
and "on exit" from the "current" form field, I attempt to store the "current" bookmark name:
Sub StoreBookmark()
strBookmark = Selection.Bookmarks(1).Name
10: If (bool_debug) Then MsgBox ("StoreBookmark() - 10: strBookmark = " & strBookmark)
End Sub
which I call from the current form field "on exit".
But when I tab out of the current form field to the next form field, the insertion point doesn't go back to the "current" but instead stays in the next form field.
Anyone have any other suggestions/insights?
Thanks,
P James Norris

How to make to click in button and open form releated in value in combox in Ms Access?

I open a form as shown here: How to use combobox to open specific form in Ms Access
But I still have a problem. When I click the button, it opens two forms immediately. What I want to do, when the value in the combobox is 1, is to open only form 1, and when the value in the combobox is 2, open form 2.
Should I correct something in my macro? How do I do it?
I personally don't like this macro builder.
Here's a proper way to do it with VBA.
Select your combobox and go in the events. In the After Update event, remove your macro code and add VBA code instead, using the option "Code Builder"
Your code should be this :
Private Sub ComboBoxColor_AfterUpdate()
On Error GoTo Err_Handler
Dim strForm As String
Select Case ComboBoxColor.Value
Case "Color1"
strForm = "Form1"
Case "Color2"
strForm = "Form2"
Case "Color3"
strForm = "Form3"
Case Else
MsgBox "I don't know what to do with this combobox value"
GoTo Exit_Sub
End Select
DoCmd.OpenForm strForm, acNormal
Exit_Sub:
Exit Sub
Err_Handler:
MsgBox Err.Description, vbExclamation, "Error " & Err.Number
Resume Exit_Sub
End Sub
Adapt ComboBoxColor with the proper name, and Form1/Form2/Form3 with the names of your forms of course (and the Color1/Color2/color3 if needed)

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

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.

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.

Command Button in msgbox vba possible?

si it possible to add a command button in the msgbox window in vba?
For example, i want to add a cancel button that stops the code rather than continuing it. I could create a new userform, but it would be nice if i save some space and use the msgbox that is already here.
VBA has several different types of MessageBoxes with built in command buttons for this very purpose. The type of buttons included in the message box is declared as the second parameter - MsgBox(Prompt, Buttons as)
The types you are probably interested in are:
vbYesNo
vbYesNoCancel
vbAbortRetryIgnore
vbOkCancel
vbRetryCancel
These Buttons return integer values that need to either be stored or used for comparison.
VBA has these integer answers stored as constants (e.g. vbOK = 1, VbCancel = 2, etc.) See Microsoft Developer Network MsgBox Function for more details on that.
Sub mySub()
Dim answer as Integer
answer = MsgBox("Would you like to choose yes?", vbYesNoCancel)
If answer = vbYes Then
'Do whatever you want
ElseIf answer = vbNo Then
'Do whatever
Else
Exit Sub
End If
End Sub
Try this:
If MsgBox("Cancel or Continue, are you sure?", vbOKCancel) = vbOK Then
'continue whatever you want to do.
End if