Ravindra BagaleCourses & study guides मराठी Track your progress

12. Macros and VBA

Excel

12.11 Excel VBA: Find the Last Row and Column

Neha has ten orders in rows 2 through 11 today. Tomorrow an extra row may arrive. A macro with 11 written into its loop would miss the new record. The next version should find the last order from a reliable field, while ignoring a note below the table. You will compare three different boundaries and show which one belongs to the question.

Say which “last row” you need

Match the boundary to the workbook layout

Think about a fictional QuickCart team using a Blinkit-style order list. These records and handling steps are invented practice. Every valid order has an Order ID in column A. Row one contains the field headings. The last known order has its ID in row eleven. A closed order may keep a visible note lower on the same sheet, and another analyst can put a calculation beside the report. Both are real worksheet content. They are not automatically new orders.

  • Record extent: Find the last occupied order key in the chosen column. This is useful when the record definition says every row in the report has a valid ID in that column. Verify what an occupied cell represents before treating it as a valid order.
  • Header width: Find the rightmost occupied cell on the header row. That tells you how far your heading extends in a stable template. It does not show whether a row below has notes or other data beyond those headings.
  • Worksheet content extent: Look for the placement of any formula or matching value within the sheet. A note below the table or a formula to its right changes this extent. Use this boundary if the job truly needs content from anywhere on the worksheet.
  • Table membership: When the source is an Excel Table, choose its named table object. Check which rows are inside it. The table can contain an empty body row depending on its current layout, and text well outside it does not become a table member.
Column A holds the order keys. Rows 2 to 11 contain the ten initial records, and row 12 is the next position.
Find the key boundary first, then decide whether the next row is safe and available for the action.

Separate a row number, a count and a next position

Eleven is the last row number, not the number of orders. You can subtract one to calculate the height of the data span under a header in row one. That gives ten positions. In the original exercise each position has an order key, so there are also ten IDs. If row six were blank and rows seven through eleven still had IDs, the last row and span would stay the same. The occupied key count would fall to nine. A report built for a real import should decide whether blanks are allowed or mean that someone needs to inspect the source.

The next row number after eleven is twelve. It can be an append candidate under a rule that says data occupy consecutive rows and there is free space. A separate note in another column or an existing formula on that row can make the row inappropriate to overwrite. This lesson only reports positions and never appends records. Before adding an append step, check every cell the new record would use.

Remember: A boundary needs a domain. Column A, row one, the entire worksheet and a named Table can all return correct answers to different questions.

Choose a method that matches the definition

Read four common approaches

Each approach answers a different boundary question
MethodUseful whenCheck
End upA key column determines the last rowBottom cell, header-only case and internal gaps
End leftA specific row determines the rightmost labelFar-right cell and correct header row
FindWhole-sheet content mattersSearch settings, formula or value and no match
Table objectA known Table defines the source rowsBody membership and actual row contents

Range.End moves from a specified cell to a boundary in the requested direction, much like a keyboard end-of-region command. A common pattern starts at the bottom of the key column and moves up. If the starting cell is blank, that can locate the final occupied cell above it. If data reach the very bottom, the extreme cell already qualifies as the last position. Check that directly before using End. Use the same reasoning for a header ending in the rightmost column.

Use the worksheet's own Rows.Count and Columns.Count rather than assuming that an open file supports a fixed grid size. Qualify the cells and both counts with the same worksheet object. Otherwise two workbooks of different types or an active window change could provide inconsistent context. The worksheet takes the location, and the row or column property returns the resulting number.

Lab one. Read the order key and header before building the loop

Start with exactly ten existing IDs

Create a workbook called BoundsPractice.xlsm. Add a worksheet called Orders. Put Order ID in A1. In the following columns put Date, City, Platform, Category, Qty, Amount, Mins and Status across B1:I1. Use the row positions below for the original IDs or copy the corresponding chapter 3 order data. This lab's boundary checks need only the header row and ID column. Keep worksheets with executable examples under your existing policy; a paper trace can use the same cells.

Put the ten known records under the header in column A
Worksheet rowA Order ID
2BLK-1001
3BLK-1002
4AMN-1003
5BLK-1004
6AMN-1005
7BLK-1006
8BLK-1007
9AMN-1008
10BLK-1009
11BLK-1010

Begin with these values before adding new records. The last key is A11, the rightmost header I1 is the ninth column, and the next candidate position is row 12. In a permanent import, have the report owner specify which key pattern is valid and how to identify duplicate IDs. In this lesson count occupied cells separately from the number of positions under the heading. A CountA result does not check ID shape, uniqueness or errors.

Option Explicit

Public Sub ShowOrderBounds()
    Dim ws As Worksheet
    Dim bottom As Range, rightEdge As Range, keyCells As Range
    Dim header As Variant
    Dim lastRow As Long, lastCol As Long

    Set ws = ThisWorkbook.Worksheets("Orders")
    header = ws.Range("A1").Value2
    If VarType(header) <> vbString Then
        MsgBox "Expected the Order ID header in A1."
        Exit Sub
    End If
    If StrComp(CStr(header), "Order ID", vbTextCompare) <> 0 Then
        MsgBox "Expected the Order ID header in A1."
        Exit Sub
    End If

    Set bottom = ws.Cells(ws.Rows.Count, 1)
    If IsEmpty(bottom.Value2) Then
        lastRow = bottom.End(xlUp).Row
    Else
        lastRow = bottom.Row
    End If

    Set rightEdge = ws.Cells(1, ws.Columns.Count)
    If IsEmpty(rightEdge.Value2) Then
        lastCol = rightEdge.End(xlToLeft).Column
    Else
        lastCol = rightEdge.Column
    End If

    Debug.Print "Last occupied key or header row", lastRow
    Debug.Print "Rightmost header column", lastCol
    If lastRow < 2 Then
        Debug.Print "Header only. No keys below it."
    Else
        Set keyCells = ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, 1))
        Debug.Print "Data positions", keyCells.Rows.Count
        Debug.Print "Nonempty key cells", Application.WorksheetFunction.CountA(keyCells)
        Debug.Print "Key extent", keyCells.Address
    End If

    If lastRow < ws.Rows.Count Then
        Debug.Print "Next row position to check", lastRow + 1
    Else
        Debug.Print "No next worksheet row."
    End If
End Sub
  • Check the header. The procedure expects a named report with a key in column A. It rejects an absent, erroneous or differently named header before calculating a region. The string comparison is case insensitive. The fixture intentionally uses the exact heading with one internal space.
  • Read the two axes. The bottom endpoint uses the last row and column one. The right endpoint uses row one and the last column. When either endpoint itself contains a value or formula result, its coordinate supplies the last position in that direction. That avoids moving away from the true boundary.
  • Build the key range only if it can include data. Checking lastRow before constructing the range avoids using the header as an actual record. In the known case with eleven, the body range becomes A2:A11. No records are added by creating that object.
  • Report an append candidate separately. A last data row at the bottom of the grid has no next row. A next row number in other cases is a position to check. It does not certify that the other columns are clear. This exercise makes the next position visible without editing it.

Run changes that answer different questions

  1. In your disposable workbook put the routine in a standard module and run it through Developer Macros. Open the editor's Immediate window and look for the latest results. Expect last row 11, header column 9, ten data positions, ten nonempty key cells, and next row 12.
  2. Enter a fictional new ID BLK-1011 in A12 and run again. The last key row becomes 12, the span contains eleven positions, and the next row becomes 13. The last header remains column I. Remove the isolated practice ID after reading the result.
  3. Clear A6 in a separate copy while leaving rows 7 through 11. The extent still ends at row 11 and contains ten positions, but there are only nine occupied IDs. This is the outcome a scan that stops at the first blank cannot provide. Restore the ID after checking.
  4. In a separate test version keep the column headers and remove just the ten fixture IDs. Last row is now 1 and there is no body range. Expect “Header only” and next row position 2. Restore the original fixture or close the scratch copy after the comparison.
  5. Add a new header at J1 without adding an order below it. The rightmost populated header moves from 9 to 10 while the key extent stays the same. Restore the header layout before starting the next lab.

Trace a new key beyond the original ten

  1. Record the starting extent

    A2:A11 has ten occupied IDs. Any cell below it in column A is outside the known exercise data.

  2. Add the eleventh ID

    Enter BLK-1011 into A12 in your own test copy. Keep the header row the same.

  3. Use the key column

    The endpoint search now identifies A12. The header endpoint still shows I1 because only one data cell was added.

  4. Report the new range

    The key span has eleven positions. The next candidate position is row thirteen, which needs its own check before any append.

Lab two. Compare the worksheet extent with the order extent

Make a visually separate note and formula

Use a separate tab called Scan within the BoundsPractice workbook. Give it the original A1:I1 headers and A2:A11 keys as before. Start with no other data. Now place “Internal note” in M20 and an empty-text formula in P14, as shown in the tests below. The note is deliberately outside the order table. The formula looks empty on the grid, but Excel can still find its expression under a formula-oriented search. Keep the Order sheet fixture from lab one to compare columns and rows separately.

Order keys end at row 11 with headers through I. A note at M20 extends the whole-sheet last row and column to 20 and M. A formula at P14 extends the column to P.
The furthest occupied row and column can come from different cells. These two numbers do not identify one actual populated cell at their intersection.
Public Sub ShowWorksheetExtent()
    Dim ws As Worksheet
    Dim lastByRow As Range, lastByColumn As Range

    Set ws = ThisWorkbook.Worksheets("Scan")
    Set lastByRow = ws.Cells.Find( _
        What:="*", After:=ws.Range("A1"), LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
        MatchCase:=False, MatchByte:=False, SearchFormat:=False)

    If lastByRow Is Nothing Then
        Debug.Print "No cell values or formulas found on Scan."
        Exit Sub
    End If

    Set lastByColumn = ws.Cells.Find( _
        What:="*", After:=ws.Range("A1"), LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, _
        MatchCase:=False, MatchByte:=False, SearchFormat:=False)

    If lastByColumn Is Nothing Then Exit Sub
    Debug.Print "Last occupied row", lastByRow.Row, lastByRow.Address
    Debug.Print "Last occupied column", lastByColumn.Column, lastByColumn.Address
End Sub

Inspect the exact search settings

  • Search pattern: A wildcard asterisk looks for matching content. LookIn:=xlFormulas tells this example to consider expressions and ordinary stored values. This search can include a formula even when its current output is an empty string.
  • Previous from A1: Find begins after the specified single cell according to its direction. With the backwards direction from the top-left cell, the search wraps around to the end of the chosen order. Searching by rows and by columns produces two separate maxima. These are separate questions even though both searches inspect the entire same worksheet.
  • Explicit options: Excel remembers several Find options between calls and shares them with the user interface. Setting the important options explicitly helps this macro avoid inheriting a different previous LookIn, LookAt or SearchOrder setting. It can also change the last-used values for subsequent Find use. The procedure does not change the selected worksheet cell.
  • No-match branch: Find returns Nothing when there is no hit. Nothing means that no valid object reference was assigned. Check the result before reading Row or Column. The blank sheet test makes the early branch visible without causing an object-variable error.

Run the four extent tests in isolation

  1. With only the headings and ten keys on Scan, expect the last occupied row to be 11 and the last occupied column to be 9. The last row's address is A11 in this sparse setup. The furthest column appears in I1. If you copied all the other fields too, the reported addresses at those same extrema can differ, so verify the row and column independently.
  2. Add the note in M20. Expect row 20 and column 13. The orders in A2:A11 still occupy the same key span, while a whole-sheet reader now sees an additional area. Read the note to establish what changed instead of assuming a record was appended.
  3. Add the formula below in P14. The displayed result is empty text. Expect row 20 because M20 remains the last occupied row, and column 16 because P14 is farther right. There need be no value or formula at P20. Checking that particular intersection would give the wrong conclusion about the worksheet's scope.
  4. In a separate workbook copy give Scan no values or formulas and apply an ordinary cell format if you want to distinguish style from content. Run the extent routine against that blank Scan tab and expect the no-match message. Review the worksheet name and use the blank-sheet branch as an object-handling exercise. Restore or discard the isolated copy when done.
P14: =""

Compare the whole sheet with a Table

An Excel Table supplies its own data rows and columns. This is useful if you always import orders into a table with a known name. Its DataBodyRange describes the data body excluding the header. If there is no body range available, test for Nothing before reading its properties. Count the Table's rows using its own ListRows collection if row membership is what you need. If a Table body contains physically empty cells or a blank row, membership alone does not prove that each row represents a valid order. Validate the key values separately. An outside note in M20 remains separate.

Two compatible answers: This exercise can report 11 as the last order key and 20 as the last worksheet content row. Both can be true on the same worksheet. The domain of each search decides which result matters.

Make growth and gaps predictable

Show how a fixed range misses new records

Consider 4,800 valid orders below a fixed header row one. If they are contiguous, the physical span runs from row two through row 4,801. Building the address from two fully qualified Cells objects is safer than starting with a string that depends on the active sheet. A string such as A2:A4801 is still useful to show the expected result in a note. For a new file with zero orders, the physical span does not start at A2. Check lastRow before forming a body range, since the bounds are not valid for data in that case.

Do not assume that the last matching key at 4,801 proves there are 4,800 nonempty values below the header. An internal row can be empty. Duplicate keys can count as occupied too. If the actual job is to process one row per current order, verify empties, key format and duplicate IDs separately. Some analyses can proceed with valid rows and report exclusions. Others need to reject the entire input so an incomplete set is not represented as a complete total.

Observe changes to worksheet layout before assigning more rows

  • First blank versus last occupied: A forward Do loop that stops at the first empty ID tells you where the first interruption occurs. With A6 empty and A11 occupied, that first blank is 6 while the latest occupied key is 11. These can be useful together for a template that requires contiguous records.
  • CurrentRegion versus full extent: CurrentRegion describes a contiguous block bounded by blank rows and columns. In a complete table it can match the whole body and header. An independent notes area or an intentional spacer can leave it smaller than the whole sheet. In the sparse exercise there are blank columns around the ID data, so geometry differs from a full original export.
  • UsedRange versus record membership: UsedRange describes Excel's used area. Formatting or earlier edits can leave its extent beyond the last real record. Look at the used area when troubleshooting the workbook size or layout. Use a defined key or named Table for report membership.
  • Last header versus last filled column: The rightmost header gives a schema boundary. A note or formula beyond it can make the latest occupied column on the whole sheet move. An extra heading with no data can instead move the header position while every existing record stays as it was.

Predict the output for layouts that break a shortcut

Decide what an apparently blank key means

The occupied key count treats cell contents as evidence of occupancy. A formula can return an empty string, creating a blank-looking grid cell. Microsoft documents that COUNTA can count such a result, as it can count an error value. In a row-processing report these may both be invalid IDs. Do not use occupied key cells as a synonym for validated records. Keep a separate check for the shape and contents of each supposed key. Then choose whether the procedure should stop on a bad key or report all individual problems and continue.

In the practice copy with the original ten contiguous IDs from A2 through A11, replace A11 with an empty-text formula. The content boundary can still reach row eleven, but the last genuine ID in the example becomes the one at row ten. Compare the last cell's displayed value, formula bar and the reported count. Restore the true ID afterward. This example illustrates why progressively extending a sheet with placeholder formulas can affect a scope based on cell occupancy. When the ID is the primary record key, identify actual valid IDs explicitly before counting them as records.

A saved worksheet can begin its table below row one

Some report templates use a title, preparation date and instructions in their first few rows. If the heading begins at A5 and the ten records begin at A6, the last key is A15. In the same layout the body height is fifteen minus five, or ten. The correct body begins six, not two. You cannot reuse ShowOrderBounds as written without agreeing where its header lives, because it intentionally checks A1 and reads row one for headers. This is a template change and the code should make it explicit before reading.

On paper draw these three shapes: header in row one with no data, header in row five with ten rows, and a table with a data gap before its last row. Label the header, first data position and last occupied record on each. The empty case requires a separate branch before building a data range. The offset case needs an explicitly selected header row. The gap case requires a membership rule in addition to the range height. Each shape can produce a normal-looking worksheet from the same export tool.

Use the header search to check fields as well as width

The first lab has headers from A1 through I1. If someone clears H1 but leaves I1 populated, column nine is still the far-right populated header. That number is a useful width indicator but does not catch the missing field name in the middle. In a maintained import check the expected names and columns, or resolve the required column by its recognized label. A title or unrelated column gives one more reason to avoid treating any nonempty header as a valid part of the expected schema.

Compare that with appending a valid approved new header into J1. The new width reflects the schema change, even if all orders are still present in the same ten rows. A separate procedure needing status should verify whether status stays in I or moves. If the field positions shift, named Table columns or an explicit qualified lookup can keep the source mapping aligned after a later edit. Test one representative record containing different values in the neighboring columns to detect a shifted lookup.

Troubleshoot unexpected row and column numbers

Read the reason before treating a number as an address

  1. Unexpected row one: If the header check passed and the key endpoint is row one, the routine found no occupied key below it. Inspect the actual worksheet and intended key column. If the full content is on a different tab, qualifying the wrong sheet correctly is still the wrong target. If the code reports a missing header, trace that failure before checking the row count.
  2. Unexpected row far below the expected list: Inspect that actual cell and the values around it. It might be a footnote, a formula or a different block. If it lives under the key column, even the key-column boundary can include it. A valid Table body or an explicit accepted key format helps determine which true records belong. Do not clear unexplained content from a live sheet to make the reported number smaller.
  3. Last header looks right, range still too wide: Find with a row-oriented scan or column-oriented scan reports defined content extent. A far-right formula can affect one result while a far-down note affects the other. Read both addresses. The rectangle from the top left to both maxima can include substantial blank space and need not represent the Orders table.
  4. Last Excel row occupied: The next numeric index would exceed the worksheet. The lab prints a dedicated message. Do not run a write using row count plus one. Choose an authorized layout or container for more records. A practice note at the physical bottom is enough to reason about this branch without editing the sheet just to observe it.
  5. Unexpected parts ignored: Compare the scope of the query and the source definition. An ID column scan can miss amount values on rows with no ID. A whole-sheet scan will typically see ordinary content elsewhere, which may be deliberately separated from the report. An Excel Table includes its known body rather than all adjacent cells. Interpret each method against the correct contract.

Check what could safely occupy the next row

Suppose your report gives last key row eleven and next candidate row twelve, but the Amount cell in G12 already contains a subtotal formula. A blind append of a whole order at A12:I12 could overwrite it. Look at the entire intended width, not just the key cell. If the subtotal belongs to the template, adding records may require extending an approved Table or placing the report somewhere else. The learning macro reports the next position without editing anything. This keeps the detection and action visible as different steps in the design.

In a separate invented test set, add a note in K12 outside the nine-column order width. Whether that note prevents an append depends on the real layout. If the planned record writes only A:I, the note at K could survive. If the procedure writes the entire row, it would be within the affected area. Check the intended write scope and the existing template rules. Describe those constraints instead of treating a row as all empty or all occupied from one cell.

Use your run notes to report “last occupied key 11, planned target row 12, existing formula in G12 requires review.” This is a more actionable result than “the last row is 11.” It separates detection, permission and the next decision. The same method applies when a sheet has reserved formatting, validation rules or formula columns for new rows.

Keep an audit table for competing boundary definitions

In a copied worksheet draw a small audit table outside the area being inspected, or write it on paper. The first column names the source question. The second names the search scope. The third records the observation. Record “last order key, Orders column A, row eleven,” and “rightmost schema label, Orders row one, column I.” On Scan record “last sheet content row, all Scan cells with formulas and values, row twenty at M20.” When you add the empty-text formula also record “last sheet content column, Scan, column P at P14.” Including the addresses helps someone reproduce your interpretation even if a later run changes the reported numbers.

A note placed on the same sheet as a whole-sheet search can change that search's result. That is a useful design lesson. If you write your audit lines below the dataset on Scan, the last row would now include the audit lines. Use a separate worksheet or external notes for the exercise comparison. Print the query result to Immediate without writing cells, as the demo does. This keeps the current search from changing its own inputs.

Suppose the person reading your audit wants the entire sheet for archival purposes. The maximum row and column depend on what you call content and can include separate blocks. These maxima describe the outer extent. Their bounding rectangle can include both the data and blank space. When a person wants to count records, tell them instead to inspect the selected Order ID range and verify the actual populated keys. Reporting both extents gives the archivist and analyst each a relevant answer without treating the whole workbook as one data table.

Compare the same audit after adding a real order in row twelve but leaving the note in M20. The record extent moves to twelve while the sheet extent can remain twenty. Looking only at the whole-sheet number would conceal a genuine new record. Use the readout tied to the action you intend to take after the scan. Verify the added order by its key as well as its row number.

Compare visibility with data membership

A record can remain present while it is hidden or outside a current filter result. The record question in this lab concerns the occupied positions in the template, not a subtotal of the rows the analyst currently sees. If a different process must address only visible records, specify that as its own selection rule and test a filtered fixture. Do not assume that the addresses returned by these general boundary checks prove which records are visible to a particular report user.

Ask for three answers: With row six blank, row eleven occupied and a note in M20, tell a partner the first gap, last key and last occupied sheet row. Give the job that would use each answer.

Quick checks

Choose the boundary that matches the data question

How many positions are there between row two and row eleven?

Ten positions. For a header in row one, eleven minus one gives the body height. The number of valid orders still depends on the key contents. If row six is empty and later rows remain populated, the height stays ten but the occupied key count drops by one.

Why test the starting cell when using End from the bottom of the worksheet?

If the physical bottom cell already contains an order key, it directly gives the last row. Moving up from that cell can take you to another boundary of a region. The worksheet maximum also means there is no following row for a new record in the same grid.

What does Find return on a sheet without any matching cells?

It returns Nothing instead of a Range reference. Check that result before accessing Row, Column or Address. A good no-match branch reports the absence of any cell content under the chosen search criterion and returns before attempting to use the nonexistent object.

What changes when M20 contains a note?

The worksheet-wide occupied row and column now reach row 20 and column M in the fixture. The key-column end is still row 11 because the note is in a different column. A report reader needs both numbers labeled with the method and what it includes.

Can the latest row and column come from different cells?

Yes. With M20 holding a note and P14 holding a formula, row 20 belongs to the note while column P belongs to the formula. P20 can be blank. Use the two results to describe extent and use their separate addresses to understand the actual content locations.

What does the first-gap scanner return if A6 is empty and A11 still has an ID?

The first empty key is row six. The last populated key remains row eleven. If you are checking contiguous input, both results matter. If you are finding the last possible record for a complete verification, stopping at row six would miss later keys.

Interview and discussion

Explain your choice of data boundary

When would you use a known key column instead of a whole-sheet search?

Use a key column when a valid record has a defined ID in that column and extra notes or technical workbook content are unrelated. Deciding which IDs count still needs a check. A whole-sheet search is appropriate for an inventory of where spreadsheet content exists, regardless of record purpose.

How do you handle a header-only worksheet?

Confirm that the expected header is present and look for any keys below it. If the last occupied key-or-header position is one in this template, report no body. Avoid building the body address or dividing by its row count. The next candidate row may be two but a caller still must check the planned output.

Why set the search options on both Find calls?

Excel can remember common search settings from previous calls or the Find dialog. Specify the scope, LookIn, order, direction and other relevant options so a prior search cannot silently change what the macro intends. Check Nothing before using the result and report each search criterion beside its boundary.

How can a Table help when orders are added regularly?

A known Table provides its named body rows and columns. Its membership can help separate records from a distant note. Check that a new order is included in the Table and that the body is available before reading properties. Membership still needs content validation for blank or duplicate IDs.

What additional work remains after identifying next row 12?

Confirm the grid has room and review every cell the new record will use. A formula, protected field or other report on that row may make the candidate wrong for the action. Consider the approved layout and the required output scope, then test on a disposable copy before adding any write procedure.

Six recall cards

  • Start with a domain

    Decide whether you need the last key, last header, last worksheet content or a named Table body.

  • Use the actual grid

    Read row and column counts from the intended worksheet. Check whether the extreme cell already holds content.

  • Span and count

    Eleven minus one is ten positions in the lab, but a gap can reduce the count of nonempty keys.

  • Find explicitly

    Set search criteria and check Nothing. Last occupied row and column may belong to separate cells.

  • Inspect the next position

    Row 12 is a candidate, not automatic authorization to replace whatever currently occupies the remaining columns.

  • Define a Table body

    Read the named Table and its data rows when membership defines the report. Validate actual IDs within those rows.

Microsoft references

Continue practising: explore the existing Excel Task Hub for additional exercises.