Vba excel if row hidden

According to a quick Google search, Range.Find will not find the data if the cell is hidden if you use LookIn:=xlValues. I tested this with «Test» in Cell A6 and hid the row. This code returned Nothing:

Sub TestIt()
    Dim x As Range
    Set x = Range("A1:A7").Find("Test", , xlValues, xlWhole)
    If x Is Nothing Then
        MsgBox "Nothing"
    Else
        If x.EntireRow.Hidden = True Then
            MsgBox x.Address & " is Hidden"
        Else
            MsgBox x.Address & " is Visible"
        End If
    End If
End Sub

Instead you need to use LookIn:=xlFormulas:

Sub TestIt()
    Dim x As Range
    Set x = Range("A1:A7").Find("Test", , xlFormulas, xlWhole)
    If x Is Nothing Then
        MsgBox "Nothing"
    Else
        If x.EntireRow.Hidden = True Then
            MsgBox x.Address & " is Hidden"
        Else
            MsgBox x.Address & " is Visible"
        End If
    End If
End Sub

Then you can use either:

y = x.EntireRow.Hidden

or

y = x.EntireColumn.Hidden

to get your Boolean (True if the cell is hidden and False if the cell is visible)

Всем привет!

-Друзья прошу помочь разобраться с созданием пользовательской функции, которая поможет мне определить какая строка таблицы скрыта;
-В Файле-примере сильно упрощенная ситуация, мне нужно определять какая строка скрыта в таблице около 1000 строк, строки которой будут скрываться в зависимости от различных настроек фильтров;
-Для решения этой задачи хочу сделать пользовательскую функцию, которая позволит определять для каждой конкретной строки скрыта они или нет, что затем использовать в операторе СУММЕСЛИМН, как второе условия при суммирование;
-Но код не работает, как должен, из-за того, что не понимаю синтаксис VBA, вот код:

Код
Function определятель(ByVal rCell As Range) As String
    If Rows(rCell).Height = False Then
        определятель = 1
    Else
        определятель = 2
    End If
End Function

-Так же хотел идти, через Hidden, но возникли сложности с пониманием работы оператора;

В этой статье говорится о проверке, скрыта ли строка в указанном диапазоне или на листе в Excel.

Проверьте, скрыта ли строка в выбранном диапазоне с кодом VBA
Проверьте, скрыта ли строка на листе с кодом VBA


Проверьте, скрыта ли строка в выбранном диапазоне с кодом VBA

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

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

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули. Затем скопируйте ниже код VBA в окно кода.

Код VBA: проверка скрытых строк в выбранном диапазоне

Sub HiddenRowsInRange()
'Update by Extendoffice 2018/5/15
    Dim I As Long
    Dim xStr As String
    Dim xOne, xTwo As Long
    Dim xRg, xRgVsb, xRgItem As Range
    On Error Resume Next
    Set xRg = Range("A1:A100")
    Set xRgVsb = xRg.SpecialCells(xlCellTypeVisible)
   If xRg.Count <> xRgVsb.Count Then
        For I = 1 To xRgVsb.Areas.Count - 1
            Set xRgItem = xRgVsb.Areas.Item(I)
            xOne = xRgItem.Rows(xRgItem.Rows.Count).Row
            xTwo = xRgVsb.Areas.Item(I + 1).Rows(1).Row
            xStr = xStr & Str(xOne + 1) & " --" & Str(xTwo - 1) & ","
        Next
        xStr = Left(xStr, Len(xStr) - 1)
        MsgBox "Hidden rows in selected range are:" & xStr
    Else
        MsgBox "No rows hidden"
    End If
End Sub

3. нажмите F5 ключ для запуска кода.

Тогда Microsoft Excel диалоговое окно всплывает, чтобы показать вам скрытые строки, как показано ниже.


Проверьте, скрыта ли строка на листе с кодом VBA

Приведенный ниже код VBA может помочь вам проверить скрытые строки на листе в Excel. Пожалуйста, сделайте следующее.

1. Откройте рабочий лист, который нужно проверить на наличие скрытых строк, нажмите кнопку другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули. Затем скопируйте ниже код VBA в окно кода.

Код VBA: проверьте, скрыта ли строка на листе

Sub HiddenRowsInSheet()
'Update by Extendoffice 2018/5/15
    Dim I As Long
    Dim xStr As String
    Dim xOne, xTwo As Long
    Dim xRg, xRgVsb, xRgItem As Range
    On Error Resume Next
    Set xRg = ActiveSheet.UsedRange
    Set xRgVsb = xRg.SpecialCells(xlCellTypeVisible)
    Debug.Print xRgVsb.Address
    If xRg.Count <> xRgVsb.Count Then
        For I = 1 To xRgVsb.Areas.Count - 1
            Set xRgItem = xRgVsb.Areas.Item(I)
            xOne = xRgItem.Rows(xRgItem.Rows.Count).Row
            xTwo = xRgVsb.Areas.Item(I + 1).Rows(1).Row
            xStr = xStr & Str(xOne + 1) & " --" & Str(xTwo - 1) & ","
        Next
        xStr = Left(xStr, Len(xStr) - 1)
        MsgBox "Hidden rows in active sheet are:" & xStr
    Else
        MsgBox "No rows hidden"
    End If
End Sub

3. нажмите F5 ключ для запуска кода.

Тогда Microsoft Excel диалоговое окно всплывает, чтобы показать вам скрытые строки на текущем листе, как показано ниже.

Внимание: Если теперь скрытые строки существуют в выбранном диапазоне или на листе, вы получите диалоговое окно, как показано ниже.


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

  • Как проверить, является ли первый символ в ячейке буквой или цифрой в Excel?

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

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

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

вкладка kte 201905


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

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Please Note:
This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Detecting Hidden Rows.

Written by Allen Wyatt (last updated July 23, 2022)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021


Jesse has a large worksheet that may contain hidden rows. He wonders if there is a way to find out if there are hidden rows in the worksheet other than by looking down the many rows to see what’s missing. If he unhides all the hidden rows, he still won’t be able to tell what, if any, rows may have been hidden.

One way you can identify hidden rows is to follow these general steps:

  1. In a column that has nothing in it, select all the cells that will cover the area you want to check. (You can select the entire column, if you desire, but that may be overkill.)
  2. Press Alt+; (that’s a semicolon). Excel selects only the unhidden cells in the selected range.
  3. Press X (or some other viewable character) and press Ctrl+Enter. This puts the character (X) into all the visible cells.

Unhide all the rows, and you’ll be able to easily see which cells in that column don’t have the character (X) in them. These are the rows that were previously hidden. You could also, if desired, use the same general approach, but after step 2 (instead of step 3) you could apply some pattern or color to the cells. Once you unhide all the rows, those cells without any pattern or color are the ones that were previously in hidden rows.

If you don’t want to unhide rows at all, perhaps the best way to find out the information is to use a macro. The following simple macro steps through the first 1,000 rows of a worksheet and then lists, in a message box, the rows that are hidden.

Sub ShowRows()
    Dim rng As Range
    Dim c As Range
    Dim sTemp As String

    Set rng = Range("A1:A1000")
    sTemp = ""

    For Each c in rng
        If c.EntireRow.Hidden Then
            sTemp = sTemp & "Row " & c.Row & vbCrLf
        End If
    Next c

    If sTemp > "" Then
        sTemp = "The following rows are hidden:" & vbCrLf & _
          vbCrLf & sTemp
        MsgBox sTemp
    Else
        MsgBox "There are no hidden rows"
    End If
End Sub

Note that the heart of the macro—where it determines whether a row is hidden or not—is in checking the Hidden property of the EntireRow object. If this property is True, then the row is hidden.

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I’ve prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training.
This tip (12217) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, Excel in Microsoft 365, and 2021. You can find a version of this tip for the older menu interface of Excel here: Detecting Hidden Rows.

Author Bio

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…

MORE FROM ALLEN

Using Text Boundaries

Text boundaries can help you better visualize where text can appear in your document. The feature is easy to turn on and …

Discover More

Removing a Macro from a Shortcut Key

When you assign a macro to a shortcut key, you make it easy to run the macro without ever removing your hands from the …

Discover More

Setting Default Options for Track Changes

The Track changes feature in Word is a great help in editing documents, particularly if you are working with others or …

Discover More

In conditional formatting I want to detect if the row above the current cell is hidden or visible. How can I detect if a cell is visible or not?

The only hack I can think of is:

  1. Create a column with all 1 values.
  2. Use a formula like subtotal(109,c2:c2)=1 (i.e. just on the cell I want to check) to determine if it’s visible or hidden.

Is there a way do do this without a temporary column that has to be left visible when the row is shown?


To avoid an XY problem, what I want to do is have a column that is the category for the row. The first VISIBLE row with a particular category should have a different style; later rows with the same category are slightly different. In ASCII:

cat.   item
+AAA+  aaaa
(AAA)  bbbb
(AAA)  cccc
+BBB+  dddd
(BBB)  eeee
(BBB)  ffff

If my filter hides the row with dddd then I want the row with eeee to have the +BBB+ styling instead.

Community's user avatar

asked Mar 3, 2015 at 21:08

Phrogz's user avatar

Instead of subtotal using a sum on another column, you can use subtotal using counta to see if a (known-non-blank) cell is hidden or not. For example, if column A will normally be visible (unless the row is hidden)

= IF( SUBTOTAL(103,A2)=1, "VISIBLE", "HIDDEN (or blank)" )

You can put this formula in a column that may be hidden, and it will still work.

In conditional formatting, then, you can just use: = SUBTOTAL(103,$A2)=1 to determine if the row is visible.

answered Mar 3, 2015 at 22:09

Phrogz's user avatar

PhrogzPhrogz

1,0102 gold badges13 silver badges28 bronze badges

1

As an addendum to Phrogz’s answer, if you need to check whether a cell in a column is hidden, try either of the following,

Conditional Formatting

=CELL("width",TargetCell)=0

This updates automatically as soon as a column is hidden.

Formula Check

=IF(CELL("width",TargetCell)=0, "Cell is hidden.", "Cell is visible.")

This formula will not update automatically and you would have to direct Excel to «Calculate Now» by choosing the menu option or pressing «F9».

answered Apr 28, 2015 at 2:54

Tom Bombadil's user avatar

1

This is similar to Gary’s Student’s approach.  Define the following VBA function:

Function MyRowHidden(ref As Range)
    MyRowHidden = Rows(ref.Row).Hidden
End Function

See How do I add VBA in MS Office?
if you need help with that.  Now you can use MyRowHidden(cell)
to check whether the row containing cell is hidden.

The way I devised to solve the problem uses a helper column, but you can hide it. 
Assuming that your data begin in Row 2, with the categories in Column A, enter

=OR($A1<>$A2, AND(H1,MyRowHidden(H1)))

into cell H2, and drag down.  This formula evaluates to TRUE if

  • the category in this row (A2)
    is different from the category in the preceding row (A1);
    i.e., this is the first row of a new category, or
  • the previous row should be highlighted, but is hidden.

Then simply use Conditional Formatting to highlight cell A2 if =H2 is true.

Example: raw data:

        full data set

Yeah, I’m a traditionalist; I still count Pluto as a planet. 
Here it is again with the prime numbered rows (2, 3, 5, 7, 11, and 13) hidden:

        filtered data

Of course you’ll have to enable macros in your workbook.

Community's user avatar

answered Mar 4, 2015 at 0:05

G-Man Says 'Reinstate Monica''s user avatar

To detect if the row above the active cell is Hidden, run this macro:

Sub WhatsAboveMe()
Dim r As Range
Set r = Selection
With r
    If .Row = 1 Then
        Exit Sub
    End If
    If .Offset(-1, 0).EntireRow.Hidden = True Then
        MsgBox "the row above is hidden"
    Else
        MsgBox "the row above is visible"
    End If
End With
End Sub

answered Mar 3, 2015 at 21:19

Gary's Student's user avatar

Gary’s StudentGary’s Student

19.2k6 gold badges25 silver badges38 bronze badges

1

This thread’s a little old, but in case it’s helpful to anyone, here is a way to conditionally format duplicates on a filtered table without having to use VBA.

  1. Make a column populated with 1’s

  2. Make another column and put a formula like this in it

    =IF(SUBTOTAL(103, [@ColumnWithOnlyOnesInIt])=1, [@ColumnYouWantToCheckForDuplicates], "")

  3. Put in normal duplicate conditional formatting on the column you want to check.

The formula from step 2 will copy the value from the column you want to check but only when the row is visible. That way, when duplicates are checked for, you only get the ones applicable to the filtered table. I think this may not work for zeros (or «» or whatever you choose as the «else» value in your if statement). So it may be possible to get a line zero value in your list that is highlighted as a duplicate. Other than that I’m having good luck with this method.

Community's user avatar

answered Nov 16, 2017 at 20:14

JFrizz's user avatar

I’d propose to use the following formula (on a range e.g. $A:$A):

=AND(A1=OFFSET(A1;-1;0);SUBTOTAL(103;OFFSET(A1;-1;0))=1)

What that does:

If both

  1. the cell is equal to the one above: A1=OFFSET(A1;-1;0)
  2. the cell above is visible: SUBTOTAL(103;OFFSET(A1;-1;0))=1

then the result is True thus the cell is a duplicate of a visible cell right above and should be e.g. grayed out.

Sidenote: Using the OFFSET function makes the conditional formatting will not break when an additional row is inserted.

answered Nov 18, 2018 at 1:51

Joma's user avatar

JomaJoma

1315 bronze badges

In the conditional formatting in, say, cell A11, use this rule

=AGGREGATE(3,3,A10)=0

Note the rule looks at the row directly above. The 3,3 parameter in AGGREGATE in plain English is

show the COUNTA of visible cells.

When A10 is hidden, the rule is TRUE and then you can set the conditional formatting in A11 on that. By the way, this works only if cell A10 has content.

So that you can copy this formatting down the column, there should be no absolute reference in the row in the rule. No helper column is needed for this approach.

zx485's user avatar

zx485

2,17011 gold badges17 silver badges23 bronze badges

answered Apr 30, 2020 at 19:16

Hillyman's user avatar

Here is the solution I just used:

I Created a new column C (and HID the original (Column B)).
In the new column I used the formula =SUBTOTAL(9,B2)
Which SUMS the ONE row you are interested in.
I then copied it all of the rows!

Now, when you filter using advanced filter. The values are all ZERO in this column unless they are visible (not filtered).

Then, the normal =SUMIF() works like a champ.
Just don’t accidentally use the hidden column to sum across. Sum across the SUBTOTAL() column you just created.

answered Aug 21, 2016 at 2:30

Captain Kirk's user avatar

Понравилась статья? Поделить с друзьями:
  • Vba excel if not is nothing then
  • Vba excel if not exists
  • Vba excel if not exist
  • Vba excel if label userform
  • Vba excel if isna