Excel vba send key

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.SendKeys method (Excel)

vbaxl10.chm183108

vbaxl10.chm183108

excel

Excel.Application.SendKeys

585666b9-adbc-5d04-c480-58e55ea7fb9d

04/05/2019

high

Application.SendKeys method (Excel)

Sends keystrokes to the active application.

Syntax

expression.SendKeys (Keys, Wait)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Keys Required Variant The key or key combination that you want to send to the application, as text.
Wait Optional Variant True to have Microsoft Excel wait for the keys to be processed before returning control to the macro. False (or omitted) to continue running the macro without waiting for the keys to be processed.

Remarks

This method places keystrokes in a key buffer. In some cases, you must call this method before you call the method that will use the keystrokes. For example, to send a password to a dialog box, you must call the SendKeys method before you display the dialog box.

The Keys argument can specify any single key or any key combined with Alt, Ctrl, or Shift (or any combination of those keys). Each key is represented by one or more characters, such as "a" for the character a, or "{ENTER}" for the Enter key.

To specify characters that aren’t displayed when you press the corresponding key (for example, Enter or Tab), use the codes listed in the following table. Each code in the table represents one key on the keyboard.

Key Code
BACKSPACE {BACKSPACE} or {BS}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
CLEAR {CLEAR}
DELETE or DEL {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER (numeric keypad) {ENTER}
ENTER ~ (tilde)
ESC {ESCAPE} or {ESC}
HELP {HELP}
HOME {HOME}
INS {INSERT}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
RETURN {RETURN}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 through F15 {F1} through {F15}

You can also specify keys combined with Shift and/or Ctrl and/or Alt. To specify a key combined with another key or keys, use the following table.

To combine a key with Precede the key code with
Shift + (plus sign)
Ctrl ^ (caret)
Alt % (percent sign)

Example

The following example creates a new workbook.

Application.SendKeys("^n")

The following example displays the Name Manager.

Application.SendKeys("%mn")

The following example enters the value 1234 into the Active Cell.

Application.SendKeys ("1234{Enter}")

[!includeSupport and feedback]

Excel VBA SendKeys

SendKeys in VBA language is a method to send keystrokes to the active window so we can work manually after that. Whenever we use alphabets as the keys, all the alphabets need to be in lowercase characters. It is a complex method and recommended to use only if necessary and when you are out of options.

“SendKeys” is one of the more complex topics to understand. Not many of us use this feature in VBA, but it is always good to have more knowledge on more topics. This article will show you how to use the SendKeys function. You may find it difficult to reread the article multiple times with a practical approach to learn fast and better.

Table of contents
  • Excel VBA SendKeys
    • Syntax
    • Examples to use Excel VBA SendKeys Method
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles

SendKeys-in-VBA

Syntax

Below is the syntax of the VBA SendKeys method.

VBA SendKeys Syntax

Keys or String: The kind of key that we need to send to the active application.

Wait: In this argument, we can use two things: TRUE or FALSE.

  • TRUE if you want the Excel to wait for the assigned Keys to process before returning the control to the Macro.
  • FALSE if you ignore the Wait parameter, this will be the default value. If you choose FALSE, Excel continues to run the Macro without waiting for the keys to process to the active window.

We use the keyboard’s common keys: “Ctrl, Shift, and ALT.” So, with the SendKeys method, we need to use them with special characters. The below table shows the special characters for the above three common keys.

Key Character Character Description
Ctrl ^ Caret
Shift + Plus Sign
ALT % Percent Sign

Other keys have different keys and characters. The below table shows the detailed explanation for each key.

Key Code
BACKSPACE {BACKSPACE} or (BS}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
CLEAR {CLEAR}
DELETE or DEL {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER (numeric keypad) {ENTER}
ENTER ~ {tilde}
ESCAPE {ESCAPE} or {ESC}
HELP {HELP}
HOME {HOME}
INS {INSERT}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
RETURN {RETURN}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 through F15 {F1} through {F15}

As per the requirement, we can use any of the above keys. With some practical examples, we will show you how to use SendKeys.

Examples to use Excel VBA SendKeys Method

You can download this VBA SendKeys Excel Template here – VBA SendKeys Excel Template

Example #1

Look at the below cell value.

vba sendkeys Example 1

We have values in three cells. For example, in the first cell, we have a value of “Bangalore.” So for this cell, there is a comment as the “Capital City of Karnataka.”

Now, using “SendKeys,” we try to edit this comment.

Open the Excel sheet. Go to the Visual Basic Editor, and start the VBA subprocedureSUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more.

Code:

Sub Send_Keys_Example()

End Sub

vba sendkeys Example 1-1

First, we need to select the comment cell to edit the comment. So, use the code RANGE(“A1”).Select

Code:

Sub Send_Keys_Example()

Range("A1").Select

End Sub

vba sendkeys Example 1-2

Once the cell is selected, we will act on editing the comments. Here, we must recollect the keyboard shortcutAn Excel shortcut is a technique of performing a manual task in a quicker way.read more we used to edit the comment.

We use the shortcut key “Shift + F2” to edit the comment.

Edit Comment Shortcut Key

If you press this key, it will edit the comment.

Now, open the “SendKeys” method.

vba sendkeys Example 1-3

In the SendKeys method, the character for using the SHIFT key is “+” (Plus sign), so enter the “+” sign-in code.

vba sendkeys Example 1-4

Now, plus sign works as a SHIFT key. The next key, along with SHIFT, we use is the F2 key. We need to enclose function keys with curly brackets whenever we use function keys. So, enter the function key F2 in the curly bracket.

Code:

Sub Send_Keys_Example()

Range("A1").Select

SendKeys "+{F2}"

End Sub

vba sendkeys Example 1-5

Now execute the code and see what we get.

Error Example 1-6

When we tried to execute the code, we got the message above. One of the key things we need to keep in mind is we cannot run the Macro, which uses “SendKeys” from the Visual Basic Editor window.

We need to run the code from the “Macro” list.

Close the Visual Basic EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more Window first.

Go to the “Developer” tab and click on “Macros.”

Macros Example 1-7

Now, a list of all the Macros opens up. Choose the Macro that you need to run. Our Macro name is “Send_Keys_Example,” so we will press the “Run” button.

Comment cell Example 1-8

You can see that the “Edit” comment option is enabled.

vba sendkeys Example 1-9

As you can see above, it has assigned the shortcut key of SHIFT + F2 to open the edit comment option.

Example #2

We can do this if you want to open the “Paste SpecialPaste special in Excel allows you to paste partial aspects of the data copied. There are several ways to paste special in Excel, including right-clicking on the target cell and selecting paste special, or using a shortcut such as CTRL+ALT+V or ALT+E+S.read more” window through the SendKeys method. But, first, we need to copy certain cells and then use the SendKeys.

Code:

Sub Send_Keys_Example1()

Range("A1").Copy

SendKeys "%es"

End Sub

Paste special code Example 2

Choose the Macro you need to run and click on “Run.”

Paste special Example 2-1

When you run the code, it will open below the Paste Special dialog box.

vba sendkeys Example 2-2

Things to Remember

  • The SendKeys assigns keystrokes to the active application.
  • This method is complex and recommended only if necessary and when you are out of options.
  • Whenever we use alphabets as the keys, all the alphabets need to be in lowercase characters.

Recommended Articles

This article has been a guide to SendKeys in VBA. Here, we discuss the examples of the VBA SendKeys method,  used to send keystrokes to the active window to work manually in Excel. Below you can find some useful Excel VBA articles: –

  • VBA ReDim Array
  • VBA ByVal
  • VBA String Comparison
  • VBA On Error GoTo

VBA SendKeys

Excel VBA SendKeys

In this article, we will see an outline on Excel VBA SendKeys. Have you ever thought of creating a program that saves your worksheet automatically and you don’t need to hit the Ctrl + S or Excel Save button to do so? It seems to be a fantasy, right? However, this can be done. In VBA, there is a command statement called SendKeys which allows you to send the keypresses as a command to the application in the same way as if you are using the keyboard to do the task. (Ex. Saving the File. You do Ctrl + S button-through keyboard to save a file). It is recommended to use SendKeys as the last option while you are automating any task. The reason behind this is, as we already discussed, SendKeys sends the keystrokes to the application that is currently active. What if you have an application window active at the time of code running under which you don’t want the changes to happen? It will give unexpected results, right? This is the sole reason, we should use SendKeys as the last option while automating the things. It can be used for the small automation though, where no other application environment is about to interfere with the one which you wanted the change to happen.

Syntax SendKeys Method

Following is a syntax SendKeys Method:

SendKeys(String As String, [Wait])

Where,

The first argument ‘String As String’ specifies the key combinations that you wanted to use under the program (Ex. Ctrl + S would be the key combination).

Wait would be an optional parameter which takes Boolean values TRUE and FALSE. If the wait has the value TRUE, it means the system will wait for the keys to be processed and then go to the next line and compile/run the same. If the wait value is FALSE (can keep blank), then the system will not wait for the keys to be processed and will continue to run the entire code.

Certain methods are using which you can combine the keystrokes with Ctrl, Shift or Alt.  Let’s see how we can do that Following is a table that specifies the keystroke combinations for SendKeys with Ctrl, Shift and Alt:

Key to be combined with Operator to be used preceding the keys for combination
Shift + (Keyboard Plus Sign)
Ctrl ^ (Caret Operator Sign)
Alt % (Percentage Sign)

Well, what does that mean? It means, if you want to use a keyboard combination as Ctrl + S under the code, you can use the SendKeys method and do it with SendKeys then a Caret (^) operator for Ctrl and then “s”. It will save the current worksheet in your excel file.

How to Use the SendKeys Method in Excel VBA?

We will learn how to use SendKeys Method in Excel by using the VBA Code.

You can download this VBA SendKeys Excel Template here – VBA SendKeys Excel Template

VBA SendKeys – Example #1

Let’s have some simple examples that will allow us to dive deeper into the working of the VBA SendKeys command.

In this first example, we are about to see very simple automation that automatically saves the current Excel file that is open. You don’t need to hit the Save button or Ctrl + S to save the file. Follow the steps below to achieve the result.

Step 1: Open Module from the Insert menu tab as shown below.

Insert Module

Step 2: Define a new sub-procedure that can hold your macro.

Code:

Sub Example_1()

End Sub

VBA SendKeys Example1-1

Step 3: Now, to save any file, you have a keyboard key combination as Ctrl + S. to convert this into code, we can use the caret operator (^) and then the “s” keyword as an argument to SendKeys statement.

Code:

Sub Example_1()

Application.SendKeys ("^s")

End Sub

VBA SendKeys Example1-2

Here, keyword Application specifies the Application to which we are sending the keystrokes (in this case Excel application). “^s” under the parentheses specifies the similar keyboard operation Ctrl + S.

Step 4: Run this code by hitting the Run button or by pressing the F5 key.

VBA SendKeys Example 1-3

After the successful run of this code, your file is saved.

VBA SendKeys – Example #2

Now, we are about to see, how to close a current application by sending softkeys through the macro code using the SendKeys method. Follow the steps below:

Step 1: Write the sub-procedure that can hold your macro under the module.

Code:

Sub Example_2()

End Sub

VBA SendKeys Example 2-1

Step 2: Use Application.SendKeys method to pass the keyboard softkeys to the application. Since the current VBA pane can be closed with the keyboard Alt + Q shortcut, we can use “%q” under macro.

Code:

Sub Example_2()

Application.SendKeys ("%q")

End Sub

Application Example 2-2

Step 3: Hit the Run button or F5 to run this code. As soon as you run this code, the current Visual Basic Editor will close and you will navigate to the Excel file.

VBA SendKeys Example 2-3

VBA SendKeys – Example #3

Now, we are going to write a code that automatically opens the Notepad and writes a text in it automatically. See the screenshot below:

Step 1: Write the sub-procedure that can hold your macro under the module.

Code:

Sub Example_3()

End Sub

VBA SendKeys Example 3-1

The Call Shell allows the system to open the application. The path is where the Notepad.exe is present. vbNormalFocus is an optional argument that specifies the focus on opening and restoring the application to its original size and position.

Step 2: Use Call and Sendkeys in combination so that the system can add a text in Notepad.

Code:

Sub Example_3()

Call Shell("C:WindowsSystem32Notepad.exe", vbNormalFocus)

End Sub

Call Shell Example 3-2

Step 3: Here, we are adding the text “Hello VBA!” using SendKeys to the Notepad. True specifies the waiting time for SendKeys command.

Code:

Sub Example_3()

Call Shell("C:WindowsSystem32Notepad.exe", vbNormalFocus)

Call SendKeys("Hello VBA!", True)

End Sub

VBA SendKeys Example 3-3

Step 4: Run this code by hitting the F5 key or by clicking on the Run button.

Notepad Example 3-4

This is how we can use the SendKeys method to automate the applications through VBA macro.

Things to Remember

  • Be very careful while using SendKeys since it may give unexpected results if you have multiple applications open.
  • You can use the SendKeys to automate the small tasks like saving an Excel File or Closing an Excel File etc.
  • Use the SendKeys method as a last option while you are trying to automate the things.

Recommended Article

This is a guide to VBA SendKeys. Here we discuss how to use SendKeys Method in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA While Loop
  2. VBA Environ
  3. VBA Goal Seek
  4. VBA Name Worksheet

Return to VBA Code Examples

VBA SendKeys

The VBA SendKeys method is used to send keystrokes to the active application:

Application.SendKeys ("s")

The above code will mimic pressing the “s” key on the keyboard.

The SendKeys method takes two arguments:

  • Keys – The key(s) you want to send to the application as text.
  • Wait (Optional) – This value can either be True or False. If True, then Excel waits for the keys to be processed first before running the next line of code. If False, then Excel continues to run the procedure without waiting for the keys to be processed.

SendKeys is usually used when interacting with other applications because it’s a quick and easy way to accomplish tasks. For example, you might use SendKeys when automating Internet Explorer.

However, you should be extremely careful when using the SendKeys Method since it can have unexpected results.  We recommend using SendKeys only as a last resort and/or when mistakes are tolerable (or easily detectable). 

VBA SendKeys Examples

Each key in terms of letters is represented by their character, for example a is “a”.
If you would like to use keys in combination with Ctrl, Shift or Alt then you have to precede the key code with the following:

Key Code
Ctrl ^
Shift +
Alt %

The following code uses the SendKeys Method to save the workbook:

Sub UsingSendKeys()

Application.SendKeys ("^s")

End Sub

As we mentioned before, you need to be extremely careful when using SendKeys. The following code specifies a waiting time of 10 seconds before the text is entered/sent to Notepad. By waiting 10 seconds, you allow Notepad a chance to open properly, reducing the chance of an error.

Note: This code uses the Application.Wait Method.

Sub UsingSendKeysWithWait()

Call Shell("C:Windowssystem32Notepad.Exe", vbNormalFocus)
Application.Wait (Now() + TimeValue("00:00:10"))
Call SendKeys("This is Some Text", True)

End Sub

The result after 10 seconds of waiting time is:

Using Send Keys With Waiting Time in VBA

SendKeys can be an extremely quick and easy way to accomplish tasks. However, the risks of errors are relatively high. Only use SendKeys when that risk is acceptable!

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Понравилась статья? Поделить с друзьями:
  • Excel vba selection paste all
  • Excel vba selection for
  • Excel vba selection clear all
  • Excel vba selecting a range of cells
  • Excel vba select selected row