You are here:

Excel/How to sum known columns with unknown rows using VBA


Hi Tom,

Would you be able to help me with this? I am using Excel 2007.

I have a workbook that contains multiple worksheets. Data in each worksheet has the same format, but the data range is different. The data always starts in cell N12 through cell O12, but the last row varies, e.g. the last row in sheet 1 is row 15, the last row in sheet 2 is row 20. I want to write VBA to accomplish the followings:

1. One row below the last row of the data, populate "TOTAL" in cell M?. ? represents the row number that is 1 + last row. For example, the last row in sheet 1 is 15. The "TOTAL" needs to be populated in cell M16.
2. Then sum column N staring from N12 to the last row of the data.
3. Then sum column O staring from O12 to the last row of the data.
4. Format the three cells montioned above with all boarders, arial font, and font size 8.

Thanks in advance for your help.



the following worked for me. It works on the sheets in the workbook that contains the code.

Sub abc()
Dim sh As Worksheet, lastrow As Long, i As Long
For Each sh In ThisWorkbook.Worksheets
  lastrow = sh.Cells(sh.Rows.Count, "N").End(xlUp).Row + 1
  sh.Cells(lastrow, "M").Value = "TOTAL"
  sh.Cells(lastrow, "N").Formula = "=Sum(N12:N" & lastrow - 1 & ")"
  sh.Cells(lastrow, "O").Formula = "=Sum(O12:O" & lastrow - 1 & ")"
  For i = 13 To 15
    With sh.Cells(lastrow, i)
       .BorderAround Weight:=xlMedium
       .Font.Name = "Arial"
       .Font.Size = 8
    End With
End Sub

Tom Ogilvy

About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Tom Ogilvy


Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]


Extensive experience.

Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2017 All rights reserved.