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

Как дважды щелкнуть ячейку, чтобы открыть указанный лист в Excel?

Вы хотите быстро перейти к указанному листу в книге Excel? В этой статье будет представлен метод VBA для открытия указанного рабочего листа двойным щелчком по определенной ячейке в Excel.

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


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

Чтобы открыть указанный рабочий лист, дважды щелкните ячейку в Excel, сделайте следующее.

1. Щелкните правой кнопкой мыши вкладку листа, содержащую ячейку, которую вы хотите открыть лист, щелкнув по ней. А затем нажмите Просмотреть код из контекстного меню. Смотрите скриншот:

2. В дебюте Microsoft Visual Basic для приложений окна, скопируйте следующий код VBA в окно кода.

Код VBA: дважды щелкните ячейку, чтобы открыть указанный рабочий лист в Excel

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Updated by Extendoffice 20180822
Dim xArray, xAValue As Variant
Dim xFNum As Long
Dim xStr, xStrRg, xStrSheetName As String
xRgArray = Array("A1;Sheet2", "A12;Sheet3", "A4;Sheet4", "A100;Sheet5")
On Error Resume Next
For xFNum = LBound(xRgArray) To UBound(xRgArray)
xStr = ""
xStr = xRgArray(xFNum)
xAValue = ""
xAValue = Split(xStr, ";")
xStrRg = ""
xStrRg = xAValue(0)
xStrSheetName = ""
xStrSheetName = xAValue(1)
If Not Intersect(Target, Range(xStrRg)) Is Nothing Then
Sheets(xStrSheetName).Activate
End If
Next
End Sub

Внимание: В коде VBA "A1; Лист2,A12; Лист3,A4; Лист4,A100; Лист5"означает, что двойной щелчок по ячейке A1 откроет Sheet2, двойной щелчок A2 откроет Sheet3 ..., пожалуйста, измените их в соответствии с вашими потребностями.

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

С этого момента, если дважды щелкнуть ячейку A1 на текущем листе, указанный рабочий лист будет немедленно активирован.


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

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

🤖 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
Can't get the code to open the other worksheet
This comment was minimized by the moderator on the site
Hi Will,Is there any prompts while using the code?
This comment was minimized by the moderator on the site
Can't get code to open the other sheet, can some help
This comment was minimized by the moderator on the site
hi!
It cannot accept the code for more than 59 sheets.
What code do i need to use to insert more sheets.
When it change the line the code doesnt work.
Help!
This comment was minimized by the moderator on the site
Hi Crystal

I have copied the code and edited according to the name of the worksheets. The code is running but I still cannot open the sheets, what have I done wrong?

Sub OpenbyDoubleclicking(ByVal Target As Range, Cancel As Boolean)

Dim xArray, xAvlaue As Variant '
Dim xFSum As Long
Dim xStr, xStrRg, xStrSheetname As String
xRgArray = Array("A3;FTIR", "A4;Viscometer")
On Error Resume Next
For xFNum = LBound(xRgArray) To UBound(xRgArray)
xStr = ""
xStr = xRgArray(xFNum)
xAValue = ""
xAValue = Split(xStr, ";")
xStrRg = ""
xStrRg = xAValue(0)
xStrSheetname = xAValue(1)
If Not Intersect(Target, Range(xStrRg)) Is Nothing Then _
Sheets(xStrSheetname).Active
End If
Next
End Sub


Many thanks
This comment was minimized by the moderator on the site
Hi Carl,
In your code, please replace the first line with "Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)".
Thank you for your comment. The entire code should be as follows.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim xArray, xAValue As Variant
Dim xFNum As Long
Dim xStr, xStrRg, xStrSheetName As String
xRgArray = Array("A3;FTIR", "A4;Viscometer")
On Error Resume Next
For xFNum = LBound(xRgArray) To UBound(xRgArray)
xStr = ""
xStr = xRgArray(xFNum)
xAValue = ""
xAValue = Split(xStr, ";")
xStrRg = ""
xStrRg = xAValue(0)
xStrSheetName = ""
xStrSheetName = xAValue(1)
If Not Intersect(Target, Range(xStrRg)) Is Nothing Then
Sheets(xStrSheetName).Activate
End If
Next
End Sub
This comment was minimized by the moderator on the site
Hi how can i extend my array? it stucks already and i cannot add more of this because it limits to col 1024 only for that line. pls help

xRgArray = Array("A2;Sheet2", "A3;Sheet3", "A4;Sheet4", "A5;Sheet5")
This comment was minimized by the moderator on the site
Hi Neil,
The code works well in my case even extended my array to Array = Array("A2;Sheet2", "A3;Sheet3", "A4;Sheet4", "A5;Sheet5", "A6;Sheet6").
Can you tell me your Excel version?
This comment was minimized by the moderator on the site
After you get to the desired sheet. Is there a way to copy information from a cell in that sheet and automatically go back to the cell I double clicked on originally in the first sheet?
This comment was minimized by the moderator on the site
Hi James
You need to manually click the original worksheet tab to back to it. Sorry can't take this into consideration.
This comment was minimized by the moderator on the site
Is there a way to do multiple codes for one tab? such as clicking on another cell to jump into another worksheet.

How would that code look like?
This comment was minimized by the moderator on the site
Good day,

The below VBA code can help you to solve the problem. Thanks for your comment.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim xArray As Variant
Dim xFNum As Long
Dim xStr, xStrRg, xStrSheetName As String
xRgArray = Array("A2;Sheet2", "A3;Sheet3", "A4;Sheet4", "A5;Sheet5")
On Error Resume Next
For xFNum = LBound(xRgArray) To UBound(xRgArray)
xStr = ""
xStr = xRgArray(xFNum)
xStrRg = ""
xStrRg = Left(xStr, 2)
xStrSheetName = ""
xStrSheetName = Right(xStr, Len(xStr) - 3)
If Not Intersect(Target, Range(xStrRg)) Is Nothing Then
Sheets(xStrSheetName).Activate
End If
Next
End Sub
This comment was minimized by the moderator on the site
Hi, In the line that states xStrRg = Left(xStr, 2), this picks up the cell if its a single number cell i.e. A1, A2, A3. but not if its A11, or A111. how do i write the code to allow me to use cells A1, A11, and A111?

Hope this makes sense, i'm not particularly technical!!
This comment was minimized by the moderator on the site
Good Day,
The code has been optimized again. Please have a try and thanks for your comment.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim xArray, xAValue As Variant
Dim xFNum As Long
Dim xStr, xStrRg, xStrSheetName As String
xRgArray = Array("A1;Sheet2", "A12;Sheet3", "A4;Sheet4", "A100;Sheet5")
On Error Resume Next
For xFNum = LBound(xRgArray) To UBound(xRgArray)
xStr = ""
xStr = xRgArray(xFNum)
xAValue = ""
xAValue = Split(xStr, ";")
xStrRg = ""
xStrRg = xAValue(0)
xStrSheetName = ""
xStrSheetName = xAValue(1)
If Not Intersect(Target, Range(xStrRg)) Is Nothing Then
Sheets(xStrSheetName).Activate
End If
Next
End Sub
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations