PDA

View Full Version : Solved: Reselect Field after failed OnExit Macro



fionabolt
11-20-2007, 03:36 AM
I have a Word Template with several fields in it. Some of these fields have On Exit Macros.

My issue is that I cannot get the code to reselect the field if the On Exit Macro fails.

For example:

Sub SIC()
Dim pos As String
Dim bkmRange As Range
Dim bkm As String

bkm = Selection.Bookmarks(1).Name
Set bkmRange = ActiveDocument.Bookmarks(bkm).Range
pos = ActiveDocument.Bookmarks(bkm).Range.Text

If Len(pos) < 4 Then
MsgBox "The SIC code must be 4 characters in length." _
& vbCr & "Please re-input the correct SIC code.", vbCritical, "SIC Code Error"
With Selection
.Collapse Direction:=wdCollapseStart
End With
bkmRange.Select
End
End If

End Sub


When you step through the code, the line bkmRange.Select does select the field. However, once the code has finished running, the original keystroke to exit the field is still affective and the selection point still moves.

How do I stop the selection point from moving if the user has not completed the field correctly?

Thanks
Fiona

fionabolt
11-20-2007, 08:49 AM
I've sorted it. Using an onEntry macro as well as an onExit one.

Option Explicit
Private mstrFF As String
Public Sub SICOnExit()
With GetCurrentFF
If Len(.Result) < 4 Then
MsgBox "The SIC code must be 4 characters in length." _
& vbCr & "Please re-input the correct SIC code.", vbCritical, "SIC Code Error"
mstrFF = GetCurrentFF.Name
End If
End With
End Sub
Public Sub SICOnEntry()
Dim strCurrentFF As String
If LenB(mstrFF) > 0 Then
ActiveDocument.FormFields(mstrFF).Select
mstrFF = vbNullString
End If
End Sub

Private Function GetCurrentFF() As Word.FormField
With Selection
If .FormFields.Count = 1 Then
' CheckBox or DropDown
Set GetCurrentFF = .FormFields(1)
ElseIf .FormFields.Count = 0 And .Bookmarks.Count > 0 Then
Set GetCurrentFF = ActiveDocument.FormFields _
(.Bookmarks(.Bookmarks.Count).Name)
End If
End With
End Function

with thanks to the http://www.gmayor.com/formfieldmacros.htm website.