About This Article
This article is created using an automated generation workflow leveraging generative AI. Official Microsoft documentation was reviewed to verify methods for retrieving visible cells and checking row visibility states and cell error values.
Verification Status: 📘 Official Specifications Confirmed – Physical Device Evaluation on Target Excel Not Performed
- Supported Environments, Capabilities, and Limitations
- Creating a practice table
- Check visible cell addresses using SpecialCells
- Distinguish between 0 items and cell errors based on row visibility state
- There Are Two Types of "Row Counts"
- The Role of SpecialCells
- Differentiating Between 0 Items and Error Handling
- Displayed cells are not necessarily contiguous
- Observe by changing filter criteria
- Handling blanks and manual hiding
- Exporting extraction results to another file
- Applying to practical work
- Difference between no filter and displaying all items
- Verification before handing over numerical data in operations
- Official and Primary Sources
- GitHub Samples
Supported Environments, Capabilities, and Limitations
| Item | Prerequisite |
|---|---|
| Target Products and Features | VBA and AutoFilter in desktop Excel for Windows. The article code is used in standard Excel modules. |
| Account and Required Subscription | An environment capable of using desktop Excel. The code is self-contained within the workbook and does not use cloud connections or additional services. |
| Permissions and Settings | An environment where macro execution is permitted, using a self-created practice workbook. If organizational restrictions apply, check with the administrator. |
| Capabilities | Counts the number of visible rows where column A contains a product code. The code does not modify cells or filter settings. |
| Limitations | Targets a fixed practice range. Behavior across Excel builds, as well as VBA compilation and execution, has not been verified. |
| Specification Confirmation Date | 2026-11-28 (JST) |
When you want to count only the currently displayed product codes after applying an AutoFilter to a table, specify the detail range excluding the headers.SpecialCells(xlCellTypeVisible) can be used to retrieve visible cells. When you want to count displayed rows even if the product code column is hidden, or when you want to distinguish between zero counts and cell errors, the method using EntireRow.Hidden described in the main text is appropriate.
Creating a practice table
Change the sheet name of the new workbook to "Extraction Practice" and enter the following table in cells A1:B4. Select A1:B4, go to Excel's [Data] -> [Filter] menu, and use the arrow in B1 to filter by "Active" only. This will make rows A2 and A4 visible. For the procedure, refer to Microsoft Support's Filter Guide.
| Row | Column A | Column B |
|---|---|---|
| 1 | Product Code | Status |
| 2 | P101 | Active |
| 3 | P102 | Suspended |
| 4 | P103 | Active |
Check visible cell addresses using SpecialCells
The following is a brief excerpt to explain the mechanism. When using it in a standard VBA module, place the variables and processing inside Sub. In the linked Daily Code, running CountVisibleProductRows is expected to output the addresses and count to the Immediate window. The A2:A30 in this example is the same range as the tutorial. Leave column A empty from row 5 onward. To distinguish between cases where there are 0 visible rows and cases where there is a cell error in the product code of a visible row, use the macro described in the main text under "Distinguish between 0 rows and cell errors based on row visibility State".
Dim area As Range, visible As Range, c As Range
Set area = ThisWorkbook.Worksheets("抽出練習").Range("A2:A30")
On Error Resume Next
Set visible = area.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If visible Is Nothing Then Exit Sub
For Each c In visible.Cells
If Len(Trim$(CStr(c.Value2))) > 0 Then
Debug.Print c.Address(False, False)
End If
Next c
Distinguish between 0 items and cell errors based on row visibility state
This is another example from the main text. The tutorial at the permanent link uses the SpecialCells version above, whereas this alternative example reads the visibility state on a row-by-row basis. Even if only column A is hidden, rows remain targeted as long as they are displayed, so the result range differs from the tutorial version that selects visible cells. The following macro targets only cells A2:A4 of the practice table. Since it checks whether a row is visible beforehand, if there are no visible rows, it returns 0 as a normal calculation result. If the filter condition is "Active", the expected value is 2 items; if "Stopped", 1 item; and if all target data rows are hidden, the expected value is 0. If the product code in a visible row is a cell error, it displays that cell address and aborts aggregation. To use this macro, paste the entire code below into the VBA editor opened via Alt+F11, by selecting [Insert] -> [Standard Module]. Return to Excel and select Alt+F8 from the list of CountVisibleProductCodes. Because ThisWorkbook refers to the workbook containing the code, please paste it into the same workbook as the practice table. Execution on the Windows version of Excel has not been verified.
Option Explicit
Sub CountVisibleProductCodes()
Dim sheet As Worksheet
Dim cell As Range
Dim value As Variant
Dim count As Long
Set sheet = ThisWorkbook.Worksheets("抽出練習")
For Each cell In sheet.Range("A2:A4").Cells
If Not cell.EntireRow.Hidden Then
value = cell.Value2
If IsError(value) Then
MsgBox "商品コードにセルエラーがあります: " & cell.Address(False, False)
Exit Sub
End If
If Len(Trim$(CStr(value))) > 0 Then count = count + 1
End If
Next cell
MsgBox "表示中の商品コード: " & count & " 件"
End Sub
| Conditions to change in the practice table | Display to check (expected value) |
|---|---|
| Filter column B to "Active" only | 2 items |
| Filter column B to "Stopped" only | 1 item |
| Set the filter condition in column B to a string that does not exist in the table | 0 items |
Revert to "Active" and enter =1/0 into A4 | A4 cell error displayed, with no item count |
| Change A4 back to P103 and hide only column A | 2 items |
When testing for 0 items, select "Equals" in the text filter for column B and specify, for example, "Unregistered". Even if the filter header remains, the code only references rows 2 to 4. Reverting the condition in column B to "Active" and then testing the error in A4 allows you to verify that only anomalies in the displayed rows halt the item count display. Conversely, displaying only "Stopped" excludes A4 from aggregation, making 1 item in A3 the expected value. After testing, revert the formula in A4 to the original dummy code.
There Are Two Types of "Row Counts"
Even if a product list has 100 rows, filtering might display only the 10 rows that match the criteria. Simply retrieving Excel's UsedRange or the table row count does not mean you have counted the 10 currently visible rows. On the other hand, because data remains in the original table even when hidden, you must not report the count of visible cells as the total data count. You must first decide whether the objective is the "current filter result" or the "entire source data".
The Role of SpecialCells
Microsoft Learn's Range.SpecialCells is a method that returns cells matching a specified type as a Range.xlCellTypeVisible When you specify , the currently visible cells become candidates. However, "visible cells" and "data rows containing values" are not the same thing. You must first determine whether to count blank cells, exclude headers, or account for manual hiding before specifying the range.
Differentiating Between 0 Items and Error Handling
Calling SpecialCells may result in an error, such as when no matching cells exist. Therefore, using On Error Resume Next temporarily for this operation, the materials in the excerpt and fixed link terminate processing if the result is Nothing. However, this method cannot distinguish between other errors occurring during the SpecialCells call and the absence of visible cells. To confirm 0 items, evaluate using the separate row-based example shown earlier. Continuing to ignore errors throughout the macro will mask issues such as incorrect sheet names or other execution environment problems. In the row-based macro in the main text,EntireRow refers to an entire row, andHidden to check if that row is hidden. Read only visible rows for Value2, determine error values using IsError, and then proceed to blank checks.
Displayed cells are not necessarily contiguous
There are cases where only A2 and A4 are displayed after filtering, while A3 between them is hidden. Treating such targets as a single contiguous range and simply counting rows from start to finish will include extra rows. Iterating through the visible Cells with For Each and checking whether each cell's value is non-blank yields the required count for this scenario. For large datasets, performance and the target range must be checked separately.
Observe by changing filter criteria
Changing the practice filter criterion to "Stopped" should display only P102, resulting in 1 item. Furthermore, changing it to a criterion with no matching values should result in 0 visible data rows. If the result differs from expectations, first verify the condition in column B and whether the filter range includes A1:B4. If all rows are displayed, the expected value is 3 items. If the sheet cannot be found at runtime, check the workbook where the code was pasted and the sheet name within it. If the macro does not appear in the list, verify whether the paste destination is a standard module or if macro execution is permitted by organizational policy.
Handling blanks and manual hiding
Rows where column A is blank but column B has a status entered may still be retrieved as visible cells by SpecialCells. In this sample, if the product code in column A is blank, it is not included in the count.Trim$ After removing leading and trailing half-width spaces, values with a length of 0 are excluded. Empty strings returned by formulas are excluded similarly. Normalization of full-width spaces and format validation of product codes are out of scope for this example. Conversely, if the requirement is to count blanks as rows as well, a different condition is needed. Furthermore, some operations require distinguishing between manually hidden rows and rows excluded by filters. It is important not to explain all circumstances using only the word "displayed".
Exporting extraction results to another file
Sequentially reading visible cells and saving to a CSV are separate processes. Directly copying discontinuous ranges resulting from filters may disrupt the expected order and correspondence with headers. When building export processing, design for required columns, sort order, duplicates, character encoding, and handling of output files in error conditions. Avoiding overwriting the output destination until count verification is complete is also a safety measure.
Applying to practical work
When counting displayed rows, do not rely solely on SpecialCells; clarify what constitutes a single item after extraction. Distinguish between headers, blanks, manual hiding, and permission differences, and compare results by changing conditions in your own workbook. Clarify not only the copy-and-paste code format, but also which inputs are determined to be correct, what the output destination is, and what must remain unchanged upon failure. Confirm using dummy data for public release only, and consider internal approval and backups when proceeding to process actual files.
Difference between no filter and displaying all items
Executing SpecialCells(xlCellTypeVisible) on a sheet without filters returns the currently displayed cells, which yields results close to counting all data rows in the original table. This does not mean the macro executed an extraction on its own. Before operating, check whether filters are set, which values are used as criteria, and if there are manually hidden rows, and write them down in the verification table. Reporting a count of 2 without knowing the extraction criteria makes it impossible to explain what that number means.
Additionally, when blank rows are mixed into the table, simply counting visible cells does not match counting rows where a product code has been entered. If formulas are present in the target column and the display result is an empty string, a design decision is also required on whether to treat it as having no value or to count it as a row where a formula exists. The macro in the main text evaluates cell values in column A Value2Because the data is read as-is, the count does not change due to leading zeros or digit separators added by display formatting. When counting only the presence of codes versus strictly matching the string representation of codes, defining separate input rules makes the aggregation results easier to interpret.
Verification before handing over numerical data in operations
When copying extracted counts into a report, record the filter criteria, total record count of the source data, and currently displayed count in separate fields. If you want to aggregate amounts for visible rows only, do not mix count determination with total calculation; instead, verify whether formulas or alternative aggregation methods support the extraction results. When the count changes due to modified filter criteria, it does not necessarily mean that source data was added. Reporting not only the count but also what was filtered makes it easier to reproduce the numbers later.
Official and Primary Sources
GitHub Samples
The fixed-version training material examines visible cells in A2:A30. The message displayed when visible ranges cannot be retrieved is insufficient to confirm whether the count was truly zero. Furthermore, the original article link in the fixed-version README points to a pre-migration path. To check for zero counts and cell errors, refer to the macro and expected value table using A2:A4 from this article.
