Перейти к основному содержанию

Как установить порядок табуляции ячеек или разблокированных ячеек в Excel?

Предположим, вам нужно установить порядок табуляции для определенных вами ячеек, например, нажмите клавишу Tab, чтобы перейти от ячейки B5 к C6, от C6 к D7, от D7 к E8, а затем вернуться к B5 при выходе из ячейки E8 на листе. как показано ниже. Как этого достичь? В этой статье представлен метод VBA.

Установите порядок табуляции ячеек или разблокированных ячеек с помощью кода VBA


Установите порядок табуляции ячеек или разблокированных ячеек с помощью кода VBA

Запустите указанный ниже метод VBA, чтобы установить порядок табуляции ячеек на обычном листе или разблокированных ячеек на защищенном листе.

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

2. в Microsoft Visual Basic для приложений окно, скопируйте и вставьте приведенный ниже код VBA в Code окно.

Код VBA: установить порядок табуляции ячеек или разблокированных ячеек

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim tabArray As Variant
    Dim i As Long
    tabArray = Array("B5", "C6", "D7", "E8")
    Application.ScreenUpdating = False
    For i = LBound(tabArray) To UBound(tabArray)
        If tabArray(i) = Target.Address(0, 0) Then
            If i = UBound(tabArray) Then
                Me.Range(tabArray(LBound(tabArray))).Select
            Else
                Me.Range(tabArray(i + 1)).Select
            End If
        End If
    Next i
    Application.ScreenUpdating = True
End Sub

Заметки:

1) В коде B5, C6, D7, E8 - это порядок ячеек ввода, и вы должны использовать прописную букву адреса ячейки. Вы можете изменить их в зависимости от ваших потребностей.
2) Для защищенного листа ячейки ввода должны быть разблокированы.

3. нажмите другой + Q ключи, чтобы закрыть Microsoft Visual Basic для приложений окно.

С этого момента, после ввода данных в B5, курсор переходит к C6 при нажатии клавиши Tab или Enter, затем переходит к D7 при выходе из C6, а затем переходит к D7, E8 на текущем листе.


Статьи по теме:

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (14)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
I have copied your code into my worksheet, but as soon as I close it and reopen it to use it again, the code is gone. How do I save this?
This comment was minimized by the moderator on the site
Hi Anita,
If you want to keep the VBA code for feature use, after adding the VBA code, save your workbook as an Excel Macro-enabled workbook as shown in the screenshot below. Then use the newly saved file in the future.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/Excel_macro-enabled_workbook.png
This comment was minimized by the moderator on the site
Olá, o código VBA para definir a ordem das células desejadas funcionou perfeitamente. Eu percebi que para que ele funcione, é necessário entrar com um dado na célula e pressionar TAB ou ENTER.
PERGUNTA: Você tem como fazer este código percorrer todas as células (no meu caso são 31, sendo algumas vazias e outras com valores padrão) sem ter que entrar com dados nelas, somente pressionando TAB ou ENTER. Como eu tenho algumas células vazias e outras com valores, por padrão, eu gostaria de percorrer as células sem precisar entrar com dados em todas elas novamente, mas, somente alterando as células que forem preciso alterar.att

Text translated by Google Translator
Hello, the VBA code to set the order of the desired cells worked perfectly. I realized that for it to work, it's necessary to enter data into the cell and press TAB or ENTER.
QUESTION: You can make this code go through all the cells (in my case there are 31, some being empty and others with default values) without having to enter data in them, just pressing TAB or ENTER. As I have some empty cells and others with values, by default I would like to cycle through the cells without having to enter data in all of them again, but only changing the cells that I need to change.att

This comment was minimized by the moderator on the site
Hello, New here The VBA code works until I hit a Pull Down Box, I get to the first on make my selection , hit Tab and it moves to a locked cell, It acts like a cell I did not enter any data in. Any suggestions? GlennD24
This comment was minimized by the moderator on the site
Hello, is there a way to just hit enter without entering anything and have it go to the next selection?
This comment was minimized by the moderator on the site
No me funcionó, lo coloqué en la hoja de trabajo, debe haber algún error, me podrían ayudar, necesito implementarlo en mi trabajo,

atte,

Collins Neptali Arráiz López
This comment was minimized by the moderator on the site
Thanks for the code on enter order. I am working on a spreadsheet entering barcode information and I need to span up to 300 cells and the program only lets me enter 142 cells. Is there a way to add more so I can get up to 300?



Thanks
This comment was minimized by the moderator on the site
Hi Jeanne,
Thanks for your comment.
But the code can’t be optimized to meet your needs. Sorry about that.
This comment was minimized by the moderator on the site
First select which cells you want to have unprotected.

When you protect your sheet it will automatically set the tab order according to your unprotected cells. It will Tab forward from Left to Right, and Top to Bottom; Shift+Tab backward from Right To Left, and Bottom to Top.
This comment was minimized by the moderator on the site
Dear Evan,
Thank you for sharing.
This comment was minimized by the moderator on the site
With the order that you have listed them excel does without VBA code. Make them go backwards then you got something.
This comment was minimized by the moderator on the site
Hello and thank you for the VBA code to set the tab order in a protected sheet where the form control labels and form control drop-down boxes are unlocked and the user can tab through and fill out the information in a label, and when tabbing to a drop down list select the number of items the instructions give him, and I have made progress with your code. At first I could only tab through each of the label form controls, now I sometimes hit the drop down lists. I would really enjoy a turorial on how tro do tis
This comment was minimized by the moderator on the site
Is it possible to use this same code to force tab across each row to each unprotected cell? I need to tab starting at cell A15, and then move to the next unprotected cell (C15), then E15, then G15. Once here, I need to tab to A16 and repeat the process for the remainder of the form. The reason I need this is that data is entered by barcode scanner, and some are programmed to tab, and others to enter. Thanks for your help on this. Spinaz
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations