Troubleshooting “NameError: name ‘df’ is not defined” (Cell execution order).

A NameError: name 'df' is not defined in Python in Excel means that a formula is trying to access a variable before it has been created in memory. Unlike standard Excel formulas that dynamically resolve dependencies regardless of cell position, Python in Excel executes in a strict spatial order across the worksheet: top-to-bottom, then left-to-right.

If cell B2 defines df = xl("Table1[#All]", headers=True) and cell A4 tries to use df, Excel runs cell A4 first. Because df does not yet exist, Python throws an immediate NameError.

Quick Fix: How to fix execution order NameErrors

Move the cell that defines the variable so it sits above or to the left of the cell referencing it. Python in Excel executes row-by-row (top-to-bottom, left-to-right). Placing initialization code and core DataFrame definitions in cell A1 guarantees the variable is defined before any dependent downstream formulas run.


The Root Cause: Excel’s Row-Major Python Execution

In traditional Excel modeling, the calculation engine builds a dependency tree. If cell A1 contains =B1*2 and cell B1 contains 10, Excel evaluates B1 first, regardless of where the cells sit on the grid.

Python in Excel works differently. Python runs inside a single, shared session per workbook. To preserve consistency across calculations, Microsoft executes all =PY() cells sequentially following a strict row-major (reading) order:

Execution Sequence Across the Grid:
┌──────┬──────────────┬──────────────┬──────────────┐
│      │   Column A   │   Column B   │   Column C   │
├──────┼──────────────┼──────────────┼──────────────┤
│Row 1 │ Step 1: A1   │ Step 2: B1   │ Step 3: C1   │
│Row 2 │ Step 4: A2   │ Step 5: B2   │ Step 6: C2   │
│Row 3 │ Step 7: A3   │ Step 8: B3   │ Step 9: C3   │
└──────┴──────────────┴──────────────┴──────────────┘
Example Failure:
If B2 defines "df", any cell evaluated before Step 5 (such as A1, C1, or A2)
cannot see "df" and will throw NameError.

If your code references a variable defined in a later step, the variable does not exist at the moment of evaluation.


Step-by-Step Diagnostic Routine

When NameError: name 'df' is not defined appears, use this diagnostic sequence to identify the misaligned cell:

Encounter NameError: name 'df' is not defined
                 │
                 ▼
Locate the Defining Cell (Where df = ... is assigned)
                 │
                 ▼
Check Coordinates: Is the referencing cell above or to the left?
                 │
        ┌────────┴────────┐
       YES                NO
        │                 │
        ▼                 ▼
Move defining cell      Check Workbook Scope:
above/left (e.g., A1)   Is df defined on another tab?
                          │
                 ┌────────┴────────┐
                YES                NO
                 │                 │
                 ▼                 ▼
         Check Tab Order:       Check Calculation Mode:
         Defining tab must be   Is calculation set to Manual?
         left of referencing    Press F9 or switch to Auto.
         tab.

1. Check Spatial Cell Positioning

Locate the cell where df is assigned. Check the row and column coordinates against the cell displaying the error:

  • If the error is in cell B5 and your definition is in cell C2, C2 runs after B5 because row 2, column C comes after row 5? No, row 2 runs before row 5!
  • But if the definition is in cell C5 and the error is in B5, row 5 column B evaluates before row 5 column C. B5 will fail.
  • If the definition is in cell B10 and the error is in B4, row 4 runs before row 10. B4 will fail.

Fix: Move the definition higher up or further to the left. The safest convention is to reserve column A or row 1 for data ingestion and variable definitions.

2. Check Worksheet Tab Ordering

Python variables persist across different sheets in the same workbook, but worksheet calculation order follows the tab sequence from left to right.

If Sheet2 defines df and Sheet1 references df:

  1. Excel evaluates all Python cells on Sheet1 first.
  2. Cells on Sheet1 cannot see variables created on Sheet2.
  3. Python returns NameError.

Fix: Click and drag the worksheet tab containing the variable definition so it sits to the left of any sheets that consume that variable.

3. Check for Calculation Freezes or Partial Recalculations

If your spreadsheet calculation mode is set to Manual, editing a definition cell will not update downstream cells until you trigger a recalculation. Downstream cells may remain stuck with a stale or uninitialized namespace state.

To resolve calculation stalls, see Handling “Calculation Mode” freezes when switching from Python to Manual..


Common Patterns That Cause Accidental NameErrors

Pattern 1: Variable Name Typos or Case Mismatches

Excel formula names are case-insensitive, but Python identifiers are strictly case-sensitive:

# Defined in cell A1:
df_sales = xl("SalesTable[#All]", headers=True)

# Attempted in cell A5:
result = df_Sales.describe()  # Fails: 'df_Sales' is not 'df_sales'

If you are seeing syntax issues inside the formula bar when declaring variables, review Fixing “SyntaxError: invalid syntax” in the Excel Formula Bar Python editor..

Pattern 2: Defining Variables Inside Conditional Blocks

If a variable is defined inside an if statement whose condition evaluates to False, the variable is never registered in the global namespace:

# In cell A1:
status = False
if status:
    df = xl("Table1[#All]", headers=True)

# In cell A2:
total = df.sum()  # Fails with NameError if status was False

Fix: Always initialize the variable with a default fallback (such as df = None or an empty DataFrame) before the conditional block.

Pattern 3: Circular Calculation Dependency Loops

Creating interdependent Python cells (where Cell A depends on Cell B, but Cell B calls a formula dependent on Cell A) causes calculation failures that break variable resolution. For mitigation strategies, see Handling “Recursive Calculation” errors in Python-to-Formula dependency chains..

For general guidance on keeping library calls, imports, and variables organized across your sheets, read our core reference on Managing Python Libraries in Excel: Fixing Imports and Syntax..