Skip to main content

Kutools for Office — One Suite. Five Tools. Get More Done.

How to lookup first non-zero value and return corresponding column header in Excel?

Author Xiaoyang Last modified

When working with data in Excel, it's common to need to identify the position of the first non-zero entry within a row and display the associated column header. For example, in a dataset where each row represents a different item or person and columns represent time periods or categories, you might want to know when a value first appears for each row. Manually checking each row for the first non-zero value can be time-consuming, especially as data size grows. Automating this lookup process not only improves efficiency but also reduces error, making your analyses more reliable. This article explains multiple practical ways to achieve this goal, from using versatile Excel formulas to employing VBA macros that are particularly useful for large datasets or recurring reports.

lookup first non-zero value and return corresponding column header


arrow blue right bubble Lookup the first non-zero value and return corresponding column header with formula

To efficiently identify the column header in a given row where the first non-zero value appears, you can use a built-in Excel formula. This approach is especially suitable for small to medium-sized datasets where real-time recalculation and ease of setup are important.

1. Select a blank cell to display the result; in this example, cell K2 is used.

=INDEX($B$1:$I$1,MATCH(TRUE,INDEX(B2:I2<>0,),0))

2. After entering the formula, press Enter to confirm. Then, select K2 and use the fill handle to drag the formula down to apply it to the rest of the rows as needed.

use a formula to lookup first non-zero value and return corresponding column header

Note: In the formula above, B1:I1 refers to the range of column headers you wish to return, and B2:I2 is the row data you are analyzing for the first non-zero value.

If your data starts in different columns or rows, remember to adjust the formula ranges accordingly. Also, this formula works effectively as long as there is at least one non-zero value in each analyzed row; if all values are zero, the formula will return an error. In such cases, consider wrapping the formula in IFERROR as this: =IFERROR(INDEX($B$1:$I$1,MATCH(TRUE,INDEX(B2:I2<>0,),0)),"No non-zero")to return a custom message instead of an error.

This formula-based solution is ideal when you want dynamic, instantly-updating results as your input data changes. However, for extremely large datasets, calculation speed may be affected, and you might seek a VBA approach to improve workflow automation or reduce manual operations.

arrow blue right bubble Use VBA macro to find and return the column header of the first non-zero value in each row

If you often need to perform this lookup task across many rows or on large datasets, or if you want to automate the process for efficiency, using a VBA macro is a practical alternative. This method is particularly advantageous for periodic report generation or when you're handling data tables that frequently change in size. The macro will search each specified row for the first non-zero value and return the corresponding column header to a target cell.

1. Click Developer tab > Visual Basic to open the Microsoft Visual Basic for Applications window. (If the Developer tab is not visible, you can add it via File > Options > Customize Ribbon.) In the VBA editor, click Insert > Module.

2. Copy and paste the following VBA code into the new module:

Sub LookupFirstNonZeroAndReturnHeader()
    Dim ws As Worksheet
    Dim dataRange As Range
    Dim headerRange As Range
    Dim outputCell As Range
    Dim r As Range
    Dim c As Range
    Dim firstNonZeroCol As Integer
    Dim i As Long
    Dim xTitleId As String
    On Error Resume Next
    xTitleId = "KutoolsforExcel"
    Set ws = Application.ActiveSheet
    Set dataRange = Application.InputBox("Select the data range (excluding headers):", xTitleId, Selection.Address, Type:=8)
    If dataRange Is Nothing Then Exit Sub
    Set headerRange = ws.Range(dataRange.Offset(-1, 0).Resize(1, dataRange.Columns.Count).Address)
    For i = 1 To dataRange.Rows.Count
        Set r = dataRange.Rows(i)
        firstNonZeroCol = 0
        
        For Each c In r.Columns
            If c.Value <> 0 And c.Value <> "" Then
                firstNonZeroCol = c.Column - dataRange.Columns(1).Column + 1
                Exit For
            End If
        Next c
        
        Set outputCell = r.Cells(1, r.Columns.Count + 1)
        
        If firstNonZeroCol > 0 Then
            outputCell.Value = headerRange.Cells(1, firstNonZeroCol).Value
        Else
            outputCell.Value = "No non-zero"
        End If
    Next i
    
    On Error GoTo 0
    MsgBox "Completed! Results are in the column to the right of your data.", vbInformation, "KutoolsforExcel"
End Sub

3. To run the macro, click Run button or press F5 key. A dialog box will prompt you to select the data range (excluding the column headers). After the macro executes, the column immediately to the right of the selected data will be filled with the header of the first non-zero value for each row, or a "No non-zero" message if no non-zero is found.

This VBA approach excels for repetitive tasks and is excellent for handling large datasets, reducing manual effort. However, ensure macros are enabled in your Excel environment and always back up your workbook before running code.

Note: If you encounter errors, check that your selection excludes the header row and includes only the data rows. 

a screenshot of kutools for excel ai

Unlock Excel Magic with Kutools AI

  • Smart Execution: Perform cell operations, analyze data, and create charts—all driven by simple commands.
  • Custom Formulas: Generate tailored formulas to streamline your workflows.
  • VBA Coding: Write and implement VBA code effortlessly.
  • Formula Interpretation: Understand complex formulas with ease.
  • Text Translation: Break language barriers within your spreadsheets.
Enhance your Excel capabilities with AI-powered tools. Download Now and experience efficiency like never before!

Best Office Productivity Tools

🤖 Kutools AI Aide: Revolutionize data analysis based on: Intelligent Execution   |  Generate Code  |  Create Custom Formulas  |  Analyze Data and Generate Charts  |  Invoke Kutools Functions
Popular Features: Find, Highlight or Identify Duplicates   |  Delete Blank Rows   |  Combine Columns or Cells without Losing Data   |   Round without Formula ...
Super Lookup: Multiple Criteria VLookup    Multiple Value VLookup  |   VLookup Across Multiple Sheets   |   Fuzzy Lookup ....
Advanced Drop-down List: Quickly Create Drop Down List   |  Dependent Drop Down List   |  Multi-select Drop Down List ....
Column Manager: Add a Specific Number of Columns  |  Move Columns  |  Toggle Visibility Status of Hidden Columns  |  Compare Ranges & Columns ...
Featured Features: Grid Focus   |  Design View   |   Big Formula Bar    Workbook & Sheet Manager   |  Resource Library (Auto Text)   |  Date Picker   |  Combine Worksheets   |  Encrypt/Decrypt Cells    Send Emails by List   |  Super Filter   |   Special Filter (filter bold/italic/strikethrough...) ...
Top 15 Toolsets12 Text Tools (Add Text, Remove Characters, ...)   |   50+ Chart Types (Gantt Chart, ...)   |   40+ Practical Formulas (Calculate age based on birthday, ...)   |   19 Insertion Tools (Insert QR Code, Insert Picture from Path, ...)   |   12 Conversion Tools (Numbers to Words, Currency Conversion, ...)   |   7 Merge & Split Tools (Advanced Combine Rows, Split Cells, ...)   |   ... and more
Use Kutools in your preferred language – supports English, Spanish, German, French, Chinese, and 40+ others!

Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time.  Click Here to Get The Feature You Need The Most...


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!

All Kutools add-ins. One installer

Kutools for Office suite bundles add-ins for Excel, Word, Outlook & PowerPoint plus Office Tab Pro, which is ideal for teams working across Office apps.

Excel Word Outlook Tabs PowerPoint
  • All-in-one suite — Excel, Word, Outlook & PowerPoint add-ins + Office Tab Pro
  • One installer, one license — set up in minutes (MSI-ready)
  • Works better together — streamlined productivity across Office apps
  • 30-day full-featured trial — no registration, no credit card
  • Best value — save vs buying individual add-in