Using VBA to position the cursor

With VBA, you can move the cursor to any control on a form. In programmer lingo, moving the cursor to a control is called giving that control the focus. When you type, your text appears in whatever control on a form now has the focus.

Square brackets and field names

VBA itself doesn't use square brackets. In fact, about the only time you see square brackets in VBA is when you're looking at a syntax chart, where square brackets are used to identify optional (as opposed to required) arguments.

Access, however, uses square brackets when an object name — such as a field, query, form, control, or report name — contains one or more blank spaces. Then, square brackets around the name are required. If the name contains no spaces, square brackets are optional.

Most VBA programmers use square brackets around all Access object names even when they're not required, as in the case of the [CCType].Enabled = False example. Using the square brackets makes it easier to distinguish between names that refer to Access objects and words that belong to VBA.

You can have VBA automatically move the cursor to any control on your form. This can be handy when your code can anticipate where the user is most likely to type next. You can have VBA position the cursor to the appropriate control automatically so that the user can just keep typing and not move the cursor on his own.

The same technique also lets you avoid error messages caused by trying to disable (or hide or lock) the control that has the focus. The VBA syntax for setting the focus to a specific control is controlName.SetFocus where controlName is the name of the control to which you want to move the cursor. For example, the following statement moves the cursor to a control named CCType on the form:


0 -1

Post a comment