VBA Outlook: Set cursor to specific position in e-mail

VBA - Visual Basic for Application

VBA is wonderfully suited to automating certain work processes in the Microsoft Office world and thus keeping daily tedious work and unnecessary clicks at bay. For example, you can programme a macro that automatically replies to an e-mail with a certain text. To save further clicks, you can position the cursor at a certain point in the e-mail so that you can continue writing at this position, e.g. because you want to insert an individual salutation.

For example, the automatic reply text could contain a salutation with a placeholder:

“Hello …, […]”.

where “…” should then be used to enter an individual name, for example.

Use SendKeys function

To achieve this, one can use the SendKeys function in the VBA code.

Sub ReplyMSG()
    Dim olItem As Outlook.MailItem
    Dim olReply As MailItem ' Reply

    Set olReply = olItem.Reply
    olReply.Display
    SendKeys "{Right}{Right}{Right}{Right}{Right}", True.
End Sub

In the code example shown above, a reply email is generated and displayed using the “Display” function. This is important because the SendKeys function works as if you were making a mouse or keyboard input, except that the individual keyboard or mouse inputs are passed by code.

The display call displays the reply mail and automatically places the cursor at the beginning of the text. Therefore, in our example, we pass the parameter {Right} 6 times to move the cursor 6 positions to the right. {RIGHT} stands for the right arrow key on the keyboard. This positions the cursor exactly in front of the “…” so that you can type in the name or salutation straight away.

With SendKeys all kinds of keyboard commands can be realised. For example, with {F1} you can trigger the F1 key or with {ENTER} you can simulate the Enter/Return key and thus cause a line break in the e-mail.

The second bool-type parameter that can be passed to the SendKeys function is the optional [wait] parameter. In our example, the parameter is not relevant and could be omitted. However, if further code follows SendKeys, then the parameter can be of importance. For the parameter [wait] = true determines whether to wait until SendKeys has executed all keyboard commands before executing the subsequent code. If [wait] = false, which is the default value, then the subsequent code in the function or procedure is executed immediately without waiting until all keyboard commands have been executed. This can lead to unsightly effects under certain circumstances, but depends on the VBA code in question.

Leave a Reply

Your email address will not be published. Required fields are marked *