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

Как показать первый элемент в выпадающем списке вместо пустого?

раскрывающийся список документов по умолчанию вверху 1

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

Показывать первый элемент в раскрывающемся списке вместо пустого с помощью функции проверки данных

Автоматически показывать первый элемент в раскрывающемся списке вместо пустого с кодом VBA


стрелка синий правый пузырь Показывать первый элемент в раскрывающемся списке вместо пустого с помощью функции проверки данных

На самом деле, чтобы выполнить эту работу, вам просто нужно применить определенную формулу при создании раскрывающегося списка, пожалуйста, сделайте следующее:

1. Выберите ячейки, в которые вы хотите вставить раскрывающийся список, и нажмите Данные > проверка достоверности данных > проверка достоверности данных, см. снимок экрана:

раскрывающийся список документов по умолчанию вверху 2

2. В выскочившем проверка достоверности данных диалоговое окно под Настройки , выберите Список из Разрешить раздел, а затем введите эту формулу: = СМЕЩЕНИЕ (Sheet3! $ A $ 1,0,0; COUNTA (Sheet3! $ A: $ A) -1,1) в Источник текстовое поле, см. снимок экрана:

Внимание: В этой формуле Sheet3 содержит ли рабочий лист список исходных данных, и A1 - первое значение ячейки в списке.

раскрывающийся список документов по умолчанию вверху 3

3. Затем нажмите OK Кнопка, теперь, когда вы щелкаете ячейки раскрывающегося списка, первый элемент данных всегда отображается вверху, независимо от того, есть ли значения ячеек, удаленных в конце исходных данных, см. снимок экрана:

раскрывающийся список документов по умолчанию вверху 4


стрелка синий правый пузырь Автоматически показывать первый элемент в раскрывающемся списке вместо пустого с кодом VBA

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

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

Код VBA: автоматически отображать первый элемент данных в раскрывающемся списке:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Updateby Extendoffice 20160725
    Dim xFormula As String
    On Error GoTo Out:
    xFormula = Target.Cells(1).Validation.Formula1
    If Left(xFormula, 1) = "=" Then
        Target.Cells(1) = Range(Mid(xFormula, 1)).Cells(1).Value
    End If
Out:
End Sub

раскрывающийся список документов по умолчанию вверху 5

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

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

🤖 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 (10)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
=OFFSET(Sheet3!$A$1,0,0,COUNTA(Sheet3!$A:$A)+2-1,1) I added +2 to the equation and that worked for me.
This comment was minimized by the moderator on the site
For the VDA code, how can I have only a certain cell range show the first item in the drop down list? Thank you in advance.
This comment was minimized by the moderator on the site
Hi, Akrupa,To solve your problem, maybe the following VBA code can help you:

<div data-tag="code">Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Updateby Extendoffice 20211206
Dim xFormula As String
Dim xRg As Range
Dim xStr As String
Dim xIndex As Integer
xIndex = 2 'Here indicates the cell number of the original data,for example,the original data is A1:A10, to display the A2 cell value, please write 2 here.
On Error GoTo Out:
xFormula = Target.Cells(1).Validation.Formula1
If Left(xFormula, 1) = "=" Then
If Target.Value <> "" Then Exit Sub
xStr = Mid(xFormula, 2)
Set xRg = Application.Range(xStr)
Target.Cells(1) = xRg.Cells(xIndex).Value
End If
Out:
End Sub
Please try, hope it can help you!
This comment was minimized by the moderator on the site
Better but not quite. Using the =OFFSET(Sheet3!$A$1,0,0,COUNTA(Sheet3!$A:$A)-1,1) method eliminates the blanks but still starts you at the bottom of the very long list. I want it to start at the top of the list.
This comment was minimized by the moderator on the site
Once again, you save the day! Thanks!
This comment was minimized by the moderator on the site
Doesn't work for me. I keep getting an error message that says, "There's a problem with this formula. Not trying to type a formula? When the first character is an equal (+) or minus (-) sign, Exel thinks it's a formula.... To get around this, type an apostrophe (') first..."
This comment was minimized by the moderator on the site
Hello!

How can I set a data validation list such that if the drop down value in the cell is deleted, the cell will automatically show a default value (i.e. "-Select-")?

For example, I have a worksheet with multiple drop down lists that I want to show a default value of "-Select-" once the sheet is opened. A user will select values from the lists that will impact the result of calculations throughout the entire spreadsheet. A user may accidentally "delete" the cell contents of the lists. If this happens, rather than the cell becoming blank, I want the cell to show a default value of "-Select-". This scenario occurs in multiple random locations throughout the spreadsheet, not just in one localized place.

I was able to find the following VBA code so far, but it only applies the concept over a range, rather than just individual cells that contain drop down lists. The problem with what I have coded so far is that every single blank cell in the range ends up with "-Select-" in it. Some of the lists are in ranges, but some are also scattered throughout the sheet. The problem I'm having with my current code is that every single blank cell in the range ends up with "-Select-" in it. I'm trying to get this to apply over the entire worksheet to ONLY cells that are drop down lists.

Is what I'm trying to accomplish even possible?

Example file can be found here:
https://drive.google.com/file/d/1VoO8VgFs3IJ0ALwqfk0i8gt69UE4vEKW/view?usp=sharing

Example code:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cel As Range
' If Target.Cells.Count > 1 Then Exit Sub 'turning this off allows multiple cells to be selected and deleted at the same time
If Not Intersect(Target, Range("f2:p17")) Is Nothing Then
For Each cel In Range("f2:p17")
Application.EnableEvents = False
If IsEmpty(cel.Value) Then cel.Value = "-Select-"
Next cel
End If
Application.EnableEvents = True
End Sub


Thanks in advance!
This comment was minimized by the moderator on the site
How can I set a data validation list such that if the drop down value in the cell is deleted, the cell will automatically show the a default value (i.e. "-Select-")?

For example, I have a worksheet with multiple drop down lists that I want to show a default value of "-Select-" once the sheet is opened. A user will select values from the lists that will impact the result of calculations throughout the entire spreadsheet. A user may accidentally "delete" the cell contents. If this happens, rather than the cell becoming blank, I want the cell to show a default value of "-Select-". This scenario occurs in multiple random locations throughout the spreadsheet, not just in one localized place.

I was able to come up with the following VBA code so far, but I've only figured out how to apply the concept over a range, rather than just cells that contain a drop down list. The problem with what I have coded so far is that every single blank cell in the range ends up with "-Select-" in it.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cel As Range
' If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("f2:p17")) Is Nothing Then
For Each cel In Range("f2:p17")
Application.EnableEvents = False
If IsEmpty(cel.Value) Then cel.Value = "-Select-"
Next cel
End If
Application.EnableEvents = True
End Sub
This comment was minimized by the moderator on the site
select the cell in which you have put the listitem
the range for the listitem is "Opleiding"
in your VBA code:

selection.Value = Range("opleiding").Cells(2, 1)

the result is that the selected item of the listItem is the second item in the range "Opleiding"
This comment was minimized by the moderator on the site
After scroll down select to cells numeric data not come in series only first cell data come select 1,2 different cells and scroll down value not coming 1,2,3,4,5....... only first cell value coming 1,1,1,1,....
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations