Sunday 16 May 2010

What happens when you press return in Excel?

After entering data in a cell, the cursor usually moves vertically down to the next cell. The cursor can also move laterally (left or right) after data entry.

This is configurable from Excel Options->Advanced->Direction, but also from VBA as well.

The setting is controlled by the MoveAfterReturnDirection property on the Application object, which can be set to xlDown, xlToLeft or xlToRight. Doing TypeName on xlDown you will see it is defined as a Long. We can therefore define a function with a static Long that can switch input mode via a custom Keyboard Shortcut.

Sub SwitchCursorMode()
Static status As Integer
Dim msg As String
If status = xlDown Or status = 0 Then
status = xlToRight
msg = "Move Right After Data Entry"
Else
status = xlDown
msg = "Move Down After Data Entry"
End If
Application.MoveAfterReturnDirection = status
End Sub

Shove the above into Excel and then assign a keyboard shortcut. The msg string is not needed, just there for debugging.

No comments: