Макрос нажатия клавиш excel

Имитация нажатия клавиш на клавиатуре в VBA Excel с помощью оператора SendKeys, в том числе эмуляция нажатия сочетаний клавиш. Синтаксис, коды, примеры.

Параметры оператора SendKeys:

Параметр Описание
string Обязательный параметр. Строковое выражение, возвращающее код клавиши (сочетания клавиш).
wait Необязательный параметр. Логическое значение, определяющее режим ожидания.
False (по умолчанию) – контроль процедуре возвращается сразу после отправки кода клавиш.
True – перед возвратом контроля процедуре коды клавиш обрабатываются.

Имитация нажатия клавиш

Эмуляция нажатия алфавитно-цифровых клавиш из кода VBA Excel, не представляющих спецсимволы: параметру string задается значение символа в прямых кавычках, например, "А", "Абвгд", "356".

Имитация нажатия клавиш, представляющих спецсимволы: параметру string задается значение символа в фигурных скобках, например, "{^}", "{)}".

Спецсимволы, которые следует заключать в фигурные скобки: плюс +, возведение в степень ^, знак процента %, тильда ~, круглые скобки (), квадратные скобки [] и сами фигурные скобки {}. Символы фигурных скобок указываются так: "{{}" и "{}}".

Для эмуляции нажатия специальных клавиш, включая функциональные и клавиши управления курсором, используются специальные коды, заключенные в фигурные скобки.

Фигурные скобки используются и для имитации нескольких нажатий одной клавиши из кода VBA Excel. В этом случае параметр string записывается в виде {клавиша число}, где число – количество нажатий. Например: "{а 10}".

Коды специальных клавиш

Клавиша Код
BACKSPACE {BACKSPACE} или {BS}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
DEL или DELETE {DELETE} или {DEL}
СТРЕЛКА ВНИЗ {DOWN}
END {END}
ENTER {ENTER} или ~
ESC {ESC}
HELP {HELP}
HOME {HOME}
INS или INSERT {INSERT} или {INS}
СТРЕЛКА ВЛЕВО {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
PRINT SCREEN {PRTSC}
СТРЕЛКА ВПРАВО {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
СТРЕЛКА ВВЕРХ {UP}
F1 … F16 {F1}{F16}

Эмуляция сочетаний клавиш

Чтобы указать сочетание клавиш с SHIFT, CTRL, ALT или их комбинацией, необходимо добавить перед кодом клавиши один или несколько следующих кодов:

Клавиша Код
SHIFT +
CTRL ^
ALT %

Чтобы указать, что клавиши SHIFT, CTRL и ALT в любом сочетании необходимо удерживать, нажимая несколько других клавиш, заключите код для последних клавиш в круглые скобки. Например, чтобы указать, что нужно удерживать клавишу SHIFT, нажимая клавиши а, б, в, г, д, введите "+(абвгд)".

Важное примечание:
Применение оператора SendKeys может приводить к автоматическому отключению* правого цифрового блока клавиатуры (переключает на стрелки и специальные клавиши). Чтобы вернуть исходную функциональность цифрового блока, необходимо в конце процедуры применить имитацию нажатия клавиши «NUM LOCK»: SendKeys "{NUMLOCK}". К сожалению, работает не всегда.

* Обнаружено в Windows 8.1 (Excel 2016).

Примеры с оператором SendKeys

Коды примеров запускаются через кнопку на рабочем листе, иначе имитация нажатия клавиш произойдет в окне редактора VBA с записью символов внутри процедуры. Попробуйте, ради интереса, запустить код первого примера из редактора VBA.

Пример 1
Заполняем первые три ячейки столбца «A» различными значениями, имитируя нажатия клавиш из кода VBA Excel:

Sub Primer1()

‘Выбираем первую ячейку

Range(«A1»).Select

‘Нажимаем клавиши «а», «б» и «в»

SendKeys «абв»

‘Нажимаем «ENTER»

SendKeys «~»

‘Нажимаем клавиши «1», «2», «3» и «ENTER»

SendKeys «123  ~»

‘Нажимаем клавишу «7» пять раз и «ENTER»

SendKeys «{7 5} ~»

‘Активируем правый цифровой блок

‘SendKeys «{NUMLOCK}»

End Sub

Пример 2
Раскрываем с помощью кода VBA Excel автофильтр или выпадающий список (имитация нажатия сочетания клавиш ALT+↓):

Sub Primer2()

‘Выбираем ячейку с автофильтром или раскрывающимся списком

Range(«D1»).Select

‘Раскрываем список

SendKeys «%{DOWN}»

‘Активируем правый цифровой блок

‘SendKeys «{NUMLOCK}»

End Sub

Пример 3
Еще три варианта эмуляции нажатия сочетаний клавиш:

‘Создание новой книги

SendKeys «^n»

‘Открытие Диспетчера имен

SendKeys «^{F3}»

‘Открытие Диспетчера задач

SendKeys «^+{ESC}»

Функция SendKeys

Иногда возникает необходимость сымитровать пользовательский ввод с клавиатуры. Тут на помощь придет фукция SendKeys. Вот её описание:

SendKeys строка, [режим ожидания]

Этот макрос прокрутит таблицу на страницу вниз.

Sub Test()
  SendKeys («{PGDN}»)
End Sub

Режим ожидания определяет то, как будет произведен возврат. В случае TRUE возврат в процедуру будет только после обработки нажатия клавиш. Если в программе выполняется какое-нибудь длительное действие, то задержка может быть значительной. В случае FALSE функция вернет управление сразу ничего не ожидая.

В фигурные скобках указываются команды и символы:

+

^

%

~

(

)

{DEL}

{INS}

{BS}

{BREAK}

{CAPSLOCK}

{ENTER}

{DOWN}

{PGUP}

и так далее. Это не все возможные коды, полный список можно посмотреть в MSDN.

Функция, приведенная ниже, переведет курсор на страницу ниже, введет 123 и нажмет ENTER:

Sub Test()
  SendKeys («{PGDN}»)
  SendKeys («123{ENTER}»)
End Sub

Вот так можно вызвать функциональную клавишу:

Sub Test()
  SendKeys («{F1}»)
End Sub

Когда экспериментируете, запускайте макрос из активной рабочей книги.

Макрос нажатия кнопки

udarock

Дата: Воскресенье, 08.12.2013, 20:40 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 36


Репутация:

10

±

Замечаний:
20% ±


Excel 2013

Здравствуйте!
Как прописать, чтобы при нажатии кнопки, нажималась и другая кнопка на другом листе.
В приложенном файле на листе 1 есть кнопка «Сохранить», на листе 2 есть кнопка «Сохранить исходные данные».
При нажатии кнопки «Сохранить» на первом листе необходимо, чтобы нажималась кнопка «Сохранить исходные данные» на втором листе.
Как это сделать?:)

К сообщению приложен файл:

6795810.xlsm
(46.4 Kb)

 

Ответить

SkyPro

Дата: Воскресенье, 08.12.2013, 20:47 |
Сообщение № 2

Группа: Друзья

Ранг: Старожил

Сообщений: 1206


Репутация:

255

±

Замечаний:
0% ±


2010

Вывести макросы из модулей листов в обычный модуль и запускать оба макроса по нажатию кнопки «сохранить».
Я вообще в модули листа или книги помещаю только процедуры по событию. И то, чаще всего, сама процедура находится в обычном модуле.

К сообщению приложен файл:

5786462.xlsm
(45.2 Kb)


skypro1111@gmail.com

Сообщение отредактировал SkyProВоскресенье, 08.12.2013, 20:54

 

Ответить

Саня

Дата: Воскресенье, 08.12.2013, 20:53 |
Сообщение № 3

Группа: Друзья

Ранг: Ветеран

Сообщений: 1067


Репутация:

560

±

Замечаний:
0% ±


XL 2016

для листа Лист7(1)
[vba]

Код

Private Sub CommandButton1_Click()
      Application.Run «Лист8.CommandButton1_Click»
‘…

[/vba]

ps
вот так еще можно:
[vba]

Код

Лист8.CommandButton1.Value = True

[/vba]

 

Ответить

udarock

Дата: Воскресенье, 08.12.2013, 21:23 |
Сообщение № 4

Группа: Пользователи

Ранг: Новичок

Сообщений: 36


Репутация:

10

±

Замечаний:
20% ±


Excel 2013

Спасибо:)

 

Ответить

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

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA SendKeys (wallstreetmojo.com)

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

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!

В данной статье я расскажу, как назначить макросу сочетание клавиш, чтобы макрос запускался по нажатию определенных клавиш.

Файлы для скачивания:

Файл Описание Размер файла: Скачивания
Скачать этот файл (P_Macros_04.zip)Пример   11 Кб 1359

Давайте возьмем файл с предварительно записанным макросом или запишем новый макрос, как это сделать описано в статье «Как записать макрос не зная языка VBA?«.

Нажимаем в меню «Вид» кнопку «Макросы» и в выпавшем списке выбираем пункт «Макросы» или нажимаем сочетание клавиш Alt+F8:

Должно будет открыться диалоговое окно «Макрос», в этом окне выбираем наш макрос «Макрос1» и нажимаем кнопку «Параметры»:

Как назначить макросу сочетание клавиш?

После чего должно открыться диалоговое окно параметров нашего макроса, в котором в пункте «Сочетания клавиш», напротив надписи Ctrl+, в пустое поле вводим любую букву, например, «й» и нажимаем «ОК»:

kak-naznachit-makrosu-sochetanie-klavish_2.png

Данное окно закроется, в диалоговом окне «Макрос» нажимаем кнопку «Отмена», после чего окно закроется:

kak-naznachit-makrosu-sochetanie-klavish_3.png

Собственно говоря, все готово, чтобы запустить макрос переключите раскладку клавиатуры в положение «РУС», и нажмите сочетание клавиш Ctrl+й, макрос выполнится.

Важно:

Если вы попытаетесь нажать это сочетание клавиш в английской раскладке, ничего не произойдет. Я настоятельно рекомендую вам использовать для назначения сочетаний клавиш буквы русского алфавита, чтобы случайно не пересечься с сочетанием клавиш используемых MS Excel.

Если вы поставите вместо «й» «Й«, то макрос будет выполняться по нажатию клавиш Shift+Ctrl+Й, так как данная функция чувствительна к регистру.

Чтобы создать кнопку для запуска своего макроса, читайте статью «Как сделать кнопку для запуска своего макроса?»

Добавить комментарий

Понравилась статья? Поделить с друзьями:
  • Макрос нажатия enter в excel
  • Макрос на удаление пустых ячеек в excel
  • Макрос на создание новой книги excel
  • Макрос на снятие защиты с листов excel
  • Макрос на сложение excel