Совет. Другие языки - Google-Translated. Вы можете посетить English версия этой ссылки.
Войти
x
or
x
x
Регистрация
x

or

Как скрыть или отобразить столбцы на основе выбора выпадающего списка в Excel?

При использовании Excel вы можете скрывать или отображать определенные столбцы на основе выбора выпадающего списка. Например, если вы выберете «Нет» в раскрывающемся списке, столбец «С» на «Я» будет скрыт, но если вы выберете «Да», скрытые столбцы «С» на «Я» будут скрыты. Ниже показан снимок экрана.

В этой статье мы покажем вам метод VBA для скрытия или отображения столбцов на основе выбора выпадающего списка в Excel.

Скрыть или показать столбцы на основе выбора выпадающего списка в Excel


Один щелчок, чтобы переключить все скрытые столбцы, чтобы быть видимыми или невидимыми в Excel

Kutools for Excel's Переключить видимость скрытых столбцов утилита, вы можете легко переключать все скрытые столбцы, чтобы быть видимыми или невидимыми в Excel.

Kutools for Excel включает в себя более удобные инструменты Excel 300. Бесплатно, без ограничений, в 60-дни. Загрузите бесплатную пробную версию

Вкладка «Office» Включите редактирование и просмотр с вкладками в Office и упростите свою работу ...
Kutools для Excel - лучший инструмент для работы в офисе, который решит большинство ваших проблем
  • Авто текст: Создайте свои любимые диаграммы, изображения, ячейки, сложные формулы и снова использовать их быстро в будущем.
  • Больше, чем текстовые функции 20: Извлечь номер из текстовой строки; Извлечь или удалить часть текстов; Преобразование чисел и валют в английские слова ...
  • Инструменты слияния: Несколько рабочих книг и листов в одном; Объединить несколько ячеек / строк / столбцов и сохранить данные; Объединить повторяющиеся строки и суммы ...
  • Сплит Инструменты: Разбить данные на несколько листов на основе значения; Одна рабочая книга для нескольких файлов Excel, PDF или CSV; От одного столбца до нескольких столбцов ...
  • Вставить Пропуск Скрытые / отфильтрованные строки; Подсчет и сумма по цвету фона; Создать список рассылки и Отправка писем по значению ячейки...
  • Суперфильтр: Создавайте расширенные схемы фильтров и применяйте их к любым листам; Сортировать по неделям, дням, частоте и более; Фильтр жирным шрифтом, формулами, комментариями ...
  • Более чем мощные функции 300; Работает с Office 2007-2019 и 365; Поддерживает все языки; Простота развертывания в компании; Полнофункциональная 60-дневная бесплатная пробная версия.

Скрыть или показать столбцы на основе выбора выпадающего списка в Excel


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

1. Сначала создайте свой раскрывающийся список с Yes и No, который вам нужен.

2. Затем нажмите другой + F11 для открытия Microsoft Visual Basic для приложений окна.

3. Дважды щелкните имя текущего открытого листа в VBAProject чтобы открыть редактор кода.

4. Затем скопируйте и вставьте под кодом VBA в редактор кода.

Код VBA: скрывать или показывать столбцы на основе выбора выпадающего списка

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20180822
    If Target.Column = 2 And Target.Row = 3 Then
        If Target.Value = "No" Then
            Application.Columns("C:I").Select
            Application.Selection.EntireColumn.Hidden = True
        ElseIf Target.Value = "Yes" Then
            Application.Columns("C:I").Select
            Application.Selection.EntireColumn.Hidden = False
        End If
    End If
End Sub

Внимание: В приведенном выше коде столбцы = 2 и Row = 3 - это ссылка на ячейку выпадающего списка, а диапазон C: I - это столбцы, которые вы хотите скрыть или показать, - замените их на свои нужды.

5. Нажмите другой + Q ключей для выхода из Microsoft Visual Basic для приложений окна.

С этого момента, когда вы выберете «Нет» в раскрывающемся списке, все указанные столбцы будут скрыты.

Но если вы выберете «Да» в раскрывающемся списке, сразу откроются все скрытые столбцы.


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


Kutools для Excel - лучший инструмент для повышения производительности в офисе Повысьте производительность на 80%

  • Супер Формула Бар (легко редактировать несколько строк текста и формул); Макет чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон...
  • Объединить ячейки / строки / столбцы и хранение данных; Содержание сплит-клеток; Объедините дублирующиеся строки и сумму / среднее... предотвратить повторяющиеся клетки; Сравнить диапазоны...
  • Выберите Дубликат или Уникальный Ряды; Выберите пустые строки (все ячейки пусты); Супер найти и нечеткая находка во многих рабочих тетрадях; Случайный выбор ...
  • Точная копия Несколько ячеек без изменения формулы ссылки; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое ...
  • Любимые и быстро вставляемые формулы, Диапазоны, графики и рисунки; Шифрование ячеек с паролем; Создать список рассылки и отправлять электронные письма ...
  • Извлечение текстаДобавить текст, Удалить по позиции, Удалить пространство; Создание и печать промежуточных итогов подкачки; Преобразование содержимого ячеек и комментариев...
  • Суперфильтр (сохранить и применить схемы фильтров к другим листам); Расширенный поиск по месяцам / неделям / дням, частоте и более; Специальный фильтр жирным шрифтом, курсивом ...
  • Объединить рабочие тетради и рабочие листы; Объединение таблиц на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF...
  • Более чем мощные функции 300, Работает с Office 2007-2019 и 365. Поддерживает все языки. Простота развертывания в компании. Полнофункциональная 60-дневная бесплатная пробная версия.
вкладка kte 201905

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

  • Включить редактирование и чтение с вкладками в Word, Excel, PowerPoint, Издатель, Доступ, Visio и Проект.
  • Открывайте и создавайте несколько документов в новых вкладках одного и того же окна, а не в новых окнах.
  • Увеличивает вашу производительность на 50% и уменьшает сотни щелчков мышью для вас каждый день!
нижняя часть офиса
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Brian · 1 months ago
    Thanks for the code, it worked well for 2 items in drop-down list. If I have more than 2 items (say 10) in the drop-down list and have varying columns eg. if A is selected hide columns C-I, if B is selected hide columns B and D-I, if C is selected hide columns B-C and E-I and so on. How do we adjust the code?
    Thank you
  • To post as a guest, your comment is unpublished.
    RAWINNA · 2 months ago
    I used the code to work great. Thank you. But when I selected from the dropdown it active to last code or moves to the last column data. How to select dropdown every time(Column = 13 And Target.Row = 3 then) not move and can record data next column ?
    Thank you.
    Example: Private Sub Worksheet_Change(ByVal Target As Range)
    'Updated by Extendoffice 20180822
    ' If Target.Column = 13 And Target.Row = 3 Then
    If Target.Column = 13 Then
    If Target.Value = "1: Yes" Then
    Application.Columns("N:O").Select
    Application.Selection.EntireColumn.Hidden = False
    Application.Columns("P:S").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("V:Z").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("X:Z").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("AB:AK").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("AL").Select
    Application.Selection.EntireColumn.Hidden = False
    Application.Columns("AM").Select
    Application.Selection.EntireColumn.Hidden = True
    ElseIf Target.Value = "2: No" Then
    Application.Columns("N").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("O:Z").Select
    Application.Selection.EntireColumn.Hidden = False
    Application.Columns("AB:AK").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("AL").Select
    Application.Selection.EntireColumn.Hidden = True
    Application.Columns("AM").Select
    Application.Selection.EntireColumn.Hidden = False
    ElseIf Target.Value = "" Then
    Application.Columns("N:AN").Select
    Application.Selection.EntireColumn.Hidden = False
    End If
    End If
    'If Target.Column = 16 And Target.Row = 3 Then
    If Target.Column = 16 Then
    If Target.Value = "Cat" Then
    Application.Columns("V:W").Select
    Application.Selection.EntireColumn.Hidden = True
    ElseIf Target.Value = "Dog" Then
    Application.Columns("V:W").Select
    Application.Selection.EntireColumn.Hidden = False
    End If
    End If
    End Sub
  • To post as a guest, your comment is unpublished.
    Reza G. · 4 months ago
    I need helps. Why when I already copied that formula to my VBA, and I tried to play it, the whole table is hidden not just partial column which I want to hide?
    Thank you very much for your assistance.
    • To post as a guest, your comment is unpublished.
      crystal · 2 months ago
      Hi Reza G.
      The code works well in my case. Do you mind attaching a screenshot of your table range and the VBA code after change? Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Ed · 7 months ago
    I'm getting an error at xHRow = (14:24")

    I'm attempting to hide or show multiple rows depending on my C4 selection. Can you assist with what i have wrong?

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xRG As Range
    Dim xHRow As Range
    Set xRG = Range("C4")
    xHRow = ("14:24")
    If Not Intersect(Target, xRG) Is Nothing Then
    If Target.Value = "Pulled" Then
    Application.Rows(xHRow).Select
    Application.Selection.EntireRow.Hidden = True
    ElseIf Target.Value = "Replaced" Then
    Application.Rows(xHRow).Select
    Application.Selection.EntireRow.Hidden = False
    End If
    End If
    End Sub
    • To post as a guest, your comment is unpublished.
      Ed · 7 months ago
      The error is: Run-time error '91':
      Object variable or with block variable not set
  • To post as a guest, your comment is unpublished.
    Aldo Molina-Moore · 7 months ago
    Each column is a different student ( 2 in this example A and B). I have two dropdowns ( on A1 and B1). Each has "Passed" "Failed" and "Select One" as an option. Now, I managed to make it work when selecting only one dropdown (either A1 or B1). I want to be able to unhide the fields that were hidden by A1 whenever I select something on B1. The goal is to select an option on A1 and fill the rows that are left. Then select B1 and fill whichever rows are left ( Regardless of A1 selection.

    Thank you!

    Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("A1:B2")) Is Nothing Or Target.Cells.Count > 1 Then
    Exit Sub

    ElseIf Range("A1").Value = "Select One" Then
    Rows("2:15").EntireRow.Hidden = False

    ElseIf Range("A1").Value = "Passed" Then
    Rows("7").EntireRow.Hidden = False
    Rows("8:15").EntireRow.Hidden = True

    ElseIf Range("A1").Value = "Failed" Then
    Rows("7").EntireRow.Hidden = True
    Rows("8:15").EntireRow.Hidden = False

    ElseIf Range("B1").Value = "Select One" Then
    Rows("2:15").EntireRow.Hidden = False

    ElseIf Range("B1").Value = "Passed" Then
    Rows("7").EntireRow.Hidden = False
    Rows("8:15").EntireRow.Hidden = True

    ElseIf Range("B1").Value = "Failed" Then
    Rows("7").EntireRow.Hidden = True
    Rows("8:15").EntireRow.Hidden = False

    End If

    End Sub
    • To post as a guest, your comment is unpublished.
      crystal · 6 months ago
      Good Day,
      Sorry can't help you with that. Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Grant · 8 months ago
    Thank you. I used the code and it works great, but when I type into a cell below and press enter it will automatically moves the cursor back to the target box. Is there a way to work around this?
    • To post as a guest, your comment is unpublished.
      crystal · 6 months ago
      Hi Grant,
      I tried as you mentioned, but didn't find the same problem. Can you tell me your Excel verson? Thanks for commenting.
  • To post as a guest, your comment is unpublished.
    ExcelUser · 10 months ago
    The code given to hide/ unhide columns based on value selected from the drop-down list of another column works great. Thanks. But it only works for the one row.
    How to apply this for the rest of the selected number of rows in the spreadsheet. I understand we may have to define a variable for the row number and in a loop increment that. But I do not know the syntax for it. Could someone help with that please?
    • To post as a guest, your comment is unpublished.
      crystal · 9 months ago
      Hi,
      Please try the below VBA code. Hope it can help.
      Please change the range as you need.

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim xRG As Range
      Set xRG = Range("B3:B30")
      If Not Intersect(Target, xRG) Is Nothing Then
      If Target.Value = "No" Then
      Application.Columns("C:I").Select
      Application.Selection.EntireColumn.Hidden = True
      ElseIf Target.Value = "Yes" Then
      Application.Columns("C:I").Select
      Application.Selection.EntireColumn.Hidden = False
      End If
      End If
      End Sub
  • To post as a guest, your comment is unpublished.
    Guinther · 10 months ago
    My dropdown menu is on cell B23. If yes, show and if no, then hide row 29. This is the code I am using:

    Private Sub Worksheet_Change(ByVal Target As Range)
    'Updated by Extendoffice 20180822
    If Target.Column = 2 And Target.Row = 23 Then
    If Target.Value = "no" Then
    Application.Row(29).Select
    Application.Selection.EntireRow.Hidden = True
    ElseIf Target.Value = "yes" Then
    Application.Row(29).Select
    Application.Selection.EntireRow.Hidden = False
    End If
    End If
    End Sub

    But I end up with a run-time error 438 - Object doesn't support this property or method. Why? Is it something wrong in the code above?

    Thanks in advance for the help.
    • To post as a guest, your comment is unpublished.
      crystal · 9 months ago
      Hi Guinther,
      The below VBA code can help you solve the problem. Please have a try. Thank you for your comment.

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim xRG As Range
      Dim xHRow As Integer
      Set xRG = Range("B23")
      xHRow = 29
      If Not Intersect(Target, xRG) Is Nothing Then
      If Target.Value = "No" Then
      Application.Rows(xHRow).Select
      Application.Selection.EntireRow.Hidden = True
      ElseIf Target.Value = "Yes" Then
      Application.Rows(xHRow).Select
      Application.Selection.EntireRow.Hidden = False
      End If
      End If
      End Sub
      • To post as a guest, your comment is unpublished.
        Gab · 9 months ago
        Hi Crystal,


        I'm hoping you could help me with hiding/showing multiple rows. I would like to show rows 63-73 when YES is selected in cell D51. I'm using the following -


        Private Sub Worksheet_Change(ByVal Target As Range)
        Dim xRG As Range
        Dim xHRow As Integer
        Set xRG = Range("D51")
        xHRow = ("63:73")
        If Not Intersect(Target, xRG) Is Nothing Then
        If Target.Value = "No" Then
        Application.Rows(xHRow).Select
        Application.Selection.EntireRow.Hidden = True
        ElseIf Target.Value = "Yes" Then
        Application.Rows(xHRow).Select
        Application.Selection.EntireRow.Hidden = False
        End If
        End If
        End Sub



        Thank you!
        • To post as a guest, your comment is unpublished.
          crystal · 6 months ago
          Hi Gab,
          Please apply the below VBA code. Thank you for your comment.

          Private Sub Worksheet_Change(ByVal Target As Range)
          Dim xRG As Range
          Dim xHRow As String
          Set xRG = Range("D51")
          xHRow = "63:73"
          If Not Intersect(Target, xRG) Is Nothing Then
          If Target.Value = "No" Then
          Application.Rows(xHRow).Select
          Application.Selection.EntireRow.Hidden = True
          ElseIf Target.Value = "Yes" Then
          Application.Rows(xHRow).Select
          Application.Selection.EntireRow.Hidden = False
          End If
          End If
          End Sub
  • To post as a guest, your comment is unpublished.
    Maria · 10 months ago
    Basically I need to know how to refer to multiple ranges at a time. I tried but it gives error. Here's a look
    Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 2 And Target.Row = 4 Then
    If Target.Value = "January" Then
    Application.Columns("AH:NC").Select
    Application.Selection.EntireColumn.Hidden = True
    ElseIf Target.Value = " January " Then
    Application.Columns("C:AG").Select
    Application.Selection.EntireColumn.Hidden = False

    ElseIf Target.Value = "February" Then
    Application.Columns("C:AG, BJ:NC").Select
    Application.Selection.EntireColumn.Hidden = True
    ElseIf Target.Value = " February " Then
    Application.Columns("AH:BI").Select
    Application.Selection.EntireColumn.Hidden = False

    End If
    End If
    End Sub

    Note: It works for Target.Value = " January ", but for Target.Value = "February" it highlights error on this line => Application.Columns("C:AG, BJ:NC").Select

    Furthermore, once it hides on selecting a target value, it does not unhide on selecting some other target value
    • To post as a guest, your comment is unpublished.
      crystal · 9 months ago
      Hi Maria,
      Your code has been optimized. Please have a try. Hope I can help.

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim xRG As Range
      Dim xHRow As Integer
      Set xRG = Range("B4")
      If Not Intersect(Target, xRG) Is Nothing Then
      If Target.Value = "January" Then
      Application.Columns("AH:NC").Hidden = True
      Application.Columns("C:AG").Hidden = False
      ElseIf Target.Value = "February" Then
      Application.Columns("C:AG").Hidden = True
      Application.Columns("BJ:NC").Hidden = True
      Application.Columns("AH:BI").Hidden = False
      End If
      End If
      End Sub
  • To post as a guest, your comment is unpublished.
    Maria · 10 months ago
    Thank you for the helpful article. I would like to take this macro a step further: I need exactly this, but the columns that I need to hide/unhide are not necessarily in a continuous range. My columns range from C to NC. What I want is that if I select Target Value 1, it hides AH to NC, and unhide C to AG, and when I select Target Value 2, it hides C to AG and also BJ to NC, and unhide AH to BI and so on subject to Target value.
  • To post as a guest, your comment is unpublished.
    Abby · 11 months ago
    This is exactly what I need to do, but I don't want the column to be highlighted when I hide/unhide. How can I build into the code to go to the next cell?
  • To post as a guest, your comment is unpublished.
    Janice · 1 years ago
    I modified this code to hide rows instead of columns, and it works but with one minor problem. I have several data validation lists on the same worksheet, and when I select a value from these other lists, all the rows specified in my code seem to unhide automatically even if the value for the target cell is set to 'No'. Why does this happen and how can I fix it?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Dear Janice,
      Sorry for the mistake, please try the new code below. Thanks for your comment.

      Private Sub Worksheet_Change(ByVal Target As Range)
      If Target.Column = 2 And Target.Row = 3 Then
      If Target.Value = "No" Then
      Application.Columns("C:I").Select
      Application.Selection.EntireColumn.Hidden = True
      ElseIf Target.Value = "Yes" Then
      Application.Columns("C:I").Select
      Application.Selection.EntireColumn.Hidden = False
      End If
      End If
      End Sub
  • To post as a guest, your comment is unpublished.
    Jeff · 1 years ago
    Hi,
    Thanks for the code, if I want to add third option what is the syntax?
  • To post as a guest, your comment is unpublished.
    Yuhui Chan · 1 years ago
    Hi there! I have a selection of 10 items and am trying to only show rows 57 to 72 when I select one of them. I am using the following code but somehow it is not working and my dashboard does not change at all. However, when I key in something into a random cell, the page reloads and rows 57:72 become hidden. But then, it stays the same across all my selections and I cannot unhide it again through the drop box selection. May I know if anyone has an alternative suggestion? Thank you in advance!


    Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Column = 2 And Target.Row = 3 And Target.Value = "1"

    Then Application.Rows("57:72").Select Application.Selection.EntireRow.Hidden = False

    Else Application.Rows("57:72").Select Application.Selection.EntireRow.Hidden = True

    End If

    End Sub
  • To post as a guest, your comment is unpublished.
    Kara · 1 years ago
    I need assistance with a similar macro but for specified cell ranges, not a whole column. Can this be done?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Dear Kara,
      Do you mean "hide contents of specified cell ranges based on cell value"? Please post you question with details so as to help us solve the problem.
  • To post as a guest, your comment is unpublished.
    Kara · 1 years ago
    I need assistance with excel macro or formula. Can anyone help?
  • To post as a guest, your comment is unpublished.
    Anish · 1 years ago
    Can anyone help :


    If i enter value to cell A1 as " No", i want columns D:E to hide. and if i enter value as "Yes", i want columns D:E to unhide and columns F:G to hide
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Dear Anish,
      This VBA code can help you. Please have a try. Thank you for your comment.

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim xRg As Range
      Set xRg = Range("A1")
      If xRg.Address = Target.Address And Target.Value = "No" Then
      Columns("D:E").EntireColumn.Hidden = True
      ElseIf xRg.Address = Target.Address And Target.Value = "Yes" Then
      Columns("D:E").EntireColumn.Hidden = False
      Columns("F:G").EntireColumn.Hidden = True
      End If
      End Sub
  • To post as a guest, your comment is unpublished.
    Ruchi · 1 years ago
    I need to use this for Hiding 14 columns alternately based on a cell value.
    eg - If A1 = CAT, then hide columns J to V

    If A1 = BAT, Then hide columns I and K to V

    If A1 = HAT, Then hide columns I, J, and L to P

    Basically, my data is in columns I till V and I need hide columns from this range except for the one selected in the reference cell. and unhide all if "All" is selected in the reference cell.

    I tried using the same formula above in a loop but I get a "compile error - " Is there a different formula I need to use?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Dear Ruchi,
      Sorry, I don’t really get your point of “Basically, my data is in columns I till V and I need hide columns from this range except for the one selected in the reference cell. and unhide all if "All" is selected in the reference cell.”
  • To post as a guest, your comment is unpublished.
    Ryan · 1 years ago
    Thank you for the helpful article.


    I would like to take this macro a step further: I need exactly this, but with the caveat that the columns that I need to hide are not necessarily in a contiguous range and can be identified by a specific row within each column.

    What i have in mind is something like this:
    if refcell = "a", then hide all columns with "a" in row 7, else
    if refcell = "b", then hide all columns with "b" in row 7, else
    if refcell = "c", then hide all columns with "c" in row 7 else
    show all columns

    If this is possible, how would the VBA code look?
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Dear Ryan,
      Please try the following VBA code. When entering "a" into cell A1, all columns with "a" in row 7 will be hidden automatically. It also works when entering b and c in cell A1.

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim xRg As Range
      Dim xRgFind As Range
      Dim xRgUni As Range
      Dim xFirstAddress As String
      On Error Resume Next
      Application.ScreenUpdating = False
      Rows(7).EntireColumn.Hidden = False
      If Target.Address = Range("A1").Address Then
      Set xRg = Intersect(ActiveSheet.UsedRange, Rows(7))
      Set xRgFind = xRg.Find(Target.Value, , xlValues, xlWhole, , , True)
      If Not xRgFind Is Nothing Then
      xFirstAddress = xRgFind.Address
      Do
      Set xRgFind = xRg.FindNext(xRgFind)
      If xRgUni Is Nothing Then
      Set xRgUni = xRgFind
      Else
      Set xRgUni = Application.Union(xRgUni, xRgFind)
      End If
      Loop While (Not xRgFind Is Nothing) And (xRgFind.Address <> xFirstAddress)
      End If
      xRgUni.EntireColumn.Hidden = True
      End If
      Application.ScreenUpdating = True
      End Sub
      • To post as a guest, your comment is unpublished.
        Eddie · 1 years ago
        Hi Crystal,
        I'm new to this. I can't tell from your code how you define a, b, and c as values in cell A1. I basically what to do what your code does, but I need the value of A1 (or any other cell I want to use) to be a string.
        Example:
        I have a table (range of cells) that contains 1 of 3 values in Row 3. The values are ("Active", "Inactive", and "Closed". I'd like all columns that have "Inactive" or "Closed" in Row 3 to be hidden. The value in Row 3 is from an INDEX/MATCH function that pulls from another sheet in my workbook. In the other sheet I select 1 of the 3 values from a drop down list.

        How would I modify this code to look for "Inactive" or "Closed" in Row 3, and only hide those columns?


        Many thanks in advance!

        Eddie
    • To post as a guest, your comment is unpublished.
      John · 1 years ago
      hey! Did you find a solution for this? Looking for the same :D
      • To post as a guest, your comment is unpublished.
        crystal · 1 years ago
        Dear John,
        The following VBA code can help you solve the problem. When entering "a" into cell A1, all columns with "a" in row 7 will be hidden automatically. It also works when entering b and c in cell A1.

        Private Sub Worksheet_Change(ByVal Target As Range)
        Dim xRg As Range
        Dim xRgFind As Range
        Dim xRgUni As Range
        Dim xFirstAddress As String
        On Error Resume Next
        Application.ScreenUpdating = False
        Rows(7).EntireColumn.Hidden = False
        If Target.Address = Range("A1").Address Then
        Set xRg = Intersect(ActiveSheet.UsedRange, Rows(7))
        Set xRgFind = xRg.Find(Target.Value, , xlValues, xlWhole, , , True)
        If Not xRgFind Is Nothing Then
        xFirstAddress = xRgFind.Address
        Do
        Set xRgFind = xRg.FindNext(xRgFind)
        If xRgUni Is Nothing Then
        Set xRgUni = xRgFind
        Else
        Set xRgUni = Application.Union(xRgUni, xRgFind)
        End If
        Loop While (Not xRgFind Is Nothing) And (xRgFind.Address <> xFirstAddress)
        End If
        xRgUni.EntireColumn.Hidden = True
        End If
        Application.ScreenUpdating = True
        End Sub
  • To post as a guest, your comment is unpublished.
    harikumar · 2 years ago
    Have modified the code like this



    Private Sub Worksheet_Change(ByVal Target As Range)


    If Target.Column = 3 And Target.Row = 2 And Target.Value = "No"

    Then


    Application.Rows("3:90").Select


    Application.Selection.EntireRow.Hidden = True


    Else


    Application.Rows("3:90").Select


    Application.Selection.EntireRow.Hidden = False


    End If


    End Sub




    But the problem am facing is am unable to answer the yes no : as all the rows 3 to 90 are getting selected not allowing me to answer the next questions
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Dear harikumar,

      The code you provided works well for me. When selecting No from the drop-down list (which locates in cell C2), row 3:90 are hidden immediately. And selecting Yes from the drop-down list will unhide them all at once. Sorry i don't get the point of what you said about unable to answer the yes no.
  • To post as a guest, your comment is unpublished.
    Pidza · 3 years ago
    Hi,
    I have a workbook and trying to get my head around a VBA code. I have code that if I select from a drop down page1 it unhides a worksheet. I am looking for a code that I select page 1 & select a range of 3-5 from a drop down it unhides a worksheet & unhides 5 columns in the unhidden worksheet.
    Is that doable?