stop tab going to next field on error - excel VBA 2016

F0RE5T

Board Regular
Joined
Nov 4, 2014
Messages
204
Hi
I use the following code in a text box.
vUcase = UCase(TxbCCID.Value)
vUcaseLen = Len(vUcase)
If vUcaseLen <> 4 Then

MsgBox ("Cost Centre Code requires 4 chars")
TxbCCID.SetFocus
Else
TxbCCID.Value = vUcase
End If

Issue is that if less than 4 characters put in and user press TAB key then the setfocus is ignored.

Can / is there a code than can be used in the error trap so to stay in the field.

many thanks in advance for any solutions.
Forest
 

Excel Facts

Who is Mr Spreadsheet?
Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.
Hi,
you don't say which event you are using but you could try placing your code in the controls exit event which has the cancel parameter

Code:
Private Sub TxbCCID_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    vUcase = UCase(TxbCCID.Value)
    vUcaseLen = Len(vUcase)
    If vUcaseLen <> 4 Then
    
    MsgBox ("Cost Centre Code requires 4 chars")
    Cancel = True
    Else
    TxbCCID.Value = vUcase
    End If
End Sub

and see if this resolves your issue

Dave.
 
Upvote 0

Forum statistics

Threads
1,215,043
Messages
6,122,816
Members
449,095
Latest member
m_smith_solihull

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top