VBA to look up non 0 values in cell range and return multiple row and column headers

Abstract: This VBA macro identifies non-zero values in an Excel range and returns their corresponding row and column headers to a new sheet.

Created: 2026-08-07 by
This VBA solution scans a specified Excel range for any non-zero numeric values and returns the corresponding row and column headers. By iterating through cells and checking against zero, the script efficiently identifies targets without manual filtering. It uses arrays to store results, ensuring fast performance even with large datasets while providing clear output for further analysis or reporting needs.

Understanding the Logic

The core challenge in this task is not just finding a value, but mapping it back to its contextual labels. In most business scenarios, your data table will have headers in the first row (for columns) and the first column (for rows). The goal is to find every cell that contains a number greater than zero or less than negative one, then record which header belongs to that row and which belongs to that column.

A naive approach might use Find methods repeatedly, which can be slow on large ranges. Instead, we use a double loop: an outer loop for rows and an inner loop for columns. This allows us to check every single cell in the target area. We must also handle edge cases, such as empty cells, text entries, or actual zeros, ensuring only numeric non-zero values trigger a result.

If you need to adjust the width of the resulting output sheet to fit these headers comfortably, you might want to review Excel VBA Code Autofit - How to Automatically Adjust Column Width in Microsoft Excel for best practices on formatting the final display.

Preparing Your Data Structure

Before running the code, ensure your worksheet is structured logically. The macro assumes:

  • Headers Row: The top row of your data range contains unique identifiers for each column (e.g., "Jan", "Feb", "Sales").
  • Headers Column: The leftmost column of your data range contains unique identifiers for each row (e.g., "Product A", "Product B").
  • Data Range: The intersection of these headers contains the numeric values you wish to filter.

It is critical that the range you select does not include the headers themselves in the search area, or the logic may break if headers are treated as strings. For example, if your data starts at B2 and ends at F10, B1:F1 are column headers and A2:A10 are row headers. The code will search B2:F10.

The Complete VBA Solution

Below is the complete, copy-pasteable VBA module. This script creates a new worksheet named "NonZero Results" and populates it with three columns: Row Header, Column Header, and the Value found.

Sub FindNonZeroValues()
    Dim wsSource As Worksheet
    Dim wsResult As Worksheet
    Dim rngData As Range
    Dim cell As Range
    Dim rowHeader As String
    Dim colHeader As String
    Dim lastRow As Long
    Dim lastCol As Long
    Dim resultRow As Long
    
    ' Set the source worksheet (change "Sheet1" to your actual sheet name)
    Set wsSource = ThisWorkbook.Sheets("Sheet1")
    
    ' Define the data range (excluding headers)
    ' Assuming headers are in Row 1 and Column A
    lastRow = wsSource.Cells(wsSource.Rows.Count, "B").End(xlUp).Row
    lastCol = wsSource.Cells(1, wsSource.Columns.Count).End(xlToLeft).Column
    
    ' Create range from B2 to last cell
    Set rngData = wsSource.Range(wsSource.Cells(2, 2), wsSource.Cells(lastRow, lastCol))
    
    ' Delete previous results sheet if it exists
    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Sheets("NonZero Results").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    
    ' Add new result sheet
    Set wsResult = ThisWorkbook.Sheets.Add(After:=wsSource)
    wsResult.Name = "NonZero Results"
    
    ' Add headers to result sheet
    With wsResult
        .Cells(1, 1).Value = "Row Header"
        .Cells(1, 2).Value = "Column Header"
        .Cells(1, 3).Value = "Value"
    End With
    
    resultRow = 2
    
    ' Loop through each cell in the data range
    For Each cell In rngData
        ' Check if the cell contains a number and is not zero
        If IsNumeric(cell.Value) And cell.Value <> 0 Then
            ' Get Row Header from Column A
            rowHeader = wsSource.Cells(cell.Row, 1).Value
            
            ' Get Column Header from Row 1
            colHeader = wsSource.Cells(1, cell.Column).Value
            
            ' Write to result sheet
            With wsResult
                .Cells(resultRow, 1).Value = rowHeader
                .Cells(resultRow, 2).Value = colHeader
                .Cells(resultRow, 3).Value = cell.Value
            End With
            
            resultRow = resultRow + 1
        End If
    Next cell
    
    ' Optional: Auto-fit columns for better readability
    wsResult.Columns("A:C").AutoFit
    
    MsgBox "Search complete. Found " & (resultRow - 2) & " non-zero values.", vbInformation
End Sub

How to Implement the Code

  1. Open the VBA Editor: Press Alt + F11 in Excel to open the Visual Basic for Applications editor.
  2. Insert a Module: In the Project Explorer (usually on the left), right-click your workbook name, select Insert, then Module.
  3. Paste the Code: Copy the entire code block above and paste it into the blank module window on the right.
  4. Customize Sheet Names: Look for the line Set wsSource = ThisWorkbook.Sheets("Sheet1"). Change "Sheet1" to the exact name of the tab containing your data.
  5. Run the Macro: Close the VBA editor, return to Excel, press Alt + F8, select FindNonZeroValues, and click Run.

The script will automatically generate a new sheet. If you encounter issues with dropdown lists or dependent tables after generating this report, you may find Change Dropdown Value based on Table in Excel VBA for Tech Support helpful for maintaining data integrity in subsequent steps.

Optimizing for Large Datasets

The standard loop shown above works well for ranges up to 10,000 cells. However, if your dataset exceeds this, the execution time may become noticeable. To optimize, you can load the range into a Variant array, process the array in memory, and then write the results back all at once. This reduces the overhead of interacting with the Excel object model repeatedly.

Additionally, consider disabling screen updating during execution by adding Application.ScreenUpdating = False at the start of the sub and Application.ScreenUpdating = True at the end. This prevents the screen from flickering as the new sheet is created and populated, making the macro feel instant to the user.

Troubleshooting Common Errors

Runtime Error 9 (Subscript Out of Range): This usually happens if the sheet name specified in the code does not match the actual tab name in Excel. Ensure there are no trailing spaces in the string literal.

No Results Found: Verify that your "zero" values are actually stored as numbers, not as text strings like "0". Use the IsNumeric function check provided in the code to handle this correctly. If your data contains formulas that return zero, they are still recognized as numbers and will be skipped, which is the desired behavior.

Duplicate Headers: If your row or column headers are not unique, the result sheet will contain duplicate entries. This is expected behavior as each cell is processed individually. If you need to aggregate these results, consider using a Pivot Table on the generated output sheet.

Frequently Asked Questions

Can I modify the code to ignore negative numbers?

Yes, simply change the condition cell.Value <> 0 to cell.Value > 0. This ensures that only positive values are captured, excluding both zeros and negatives from your report.

What if my headers are in different locations?

You can adjust the rowHeader and colHeader assignment lines. For instance, if row headers are in Column Z, change wsSource.Cells(cell.Row, 1) to wsSource.Cells(cell.Row, 26). Always ensure the index matches the correct column letter.

How do I handle blank cells in the data range?

The IsNumeric function returns False for truly blank cells, so they are naturally ignored. However, if a cell contains an error value (like #N/A), IsNumeric also returns False. If you need to catch specific errors, you would add an additional check using On Error Resume Next around the value read operation.

Can I run this on multiple sheets at once?

The current code targets a single hardcoded sheet. To loop through all sheets, you would wrap the logic inside a For Each ws In ThisWorkbook.Worksheets loop, excluding the result sheet itself to prevent infinite loops or errors.

Why is my result sheet creating duplicates?

If you run the macro multiple times without deleting the old result sheet manually, the code includes a deletion step at the beginning. If you remove that step, you must manually clear the sheet before re-running to avoid appending new results to old ones.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More