I have an Excel Spreadsheet that I generated dynamically using SQL and VB.NET. The number of columns (2) will never change, however the number of records will change according to what data the user has specified. After the SQL has run and has filled the spreadsheet, I need to add a record at the bottom of the table that displays the total(int value) of the records in column 2.
Something like:
xlSheet.Range(bottom record, column1) = “Total”
xlSheet.Range(bottom record, column2) = Sum of all above records in column 2
I am using VS 2010 and Excel 2010.
My tables resembles this:
*Group* *Refered Cases*
4H BOSS 0
4H BSG 0
4H SALES AND MKTG 0
ACCOUNTS RECEIVABLE 0
ASSET MANAGEMENT 0
AUDIT 0
BOSS 0
CORPORATE BSG 0
CUSTOMER SUPPORT 0
NETWORK ENGINEERING 0
PRODUCTION ENGINEERING 0
PRODUCTION OPERATIONS 0
SECURITY 0
SNFAL PRODUCT TEAM 0
VOICE SERVICES 0
XEROX 0
ANSWER:
Ok, I was able to use the following code to dynamically find the last cell of the first column and input “TOTAL” into the cell and also format it accordingly.
Dim lTotalRows As Long, lTotalCols As Long
lTotalRows = xlSheet.UsedRange.Rows.Count
lTotalCols = xlSheet.UsedRange.Columns.Count
With xlSheet.Range("A" & (lTotalRows + 1).ToString) 'Dynamically finds the last cell of the first column, and sets it equal to "Total" and formats the cell
.Value = "TOTAL"
.Interior.ColorIndex = 41 'Cell Background Changed to Black
.Columns("A:B").EntireColumn.AutoFit()
With .Font
.ColorIndex = 2 'Cell Font Changed to White
.Bold = True
.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleSingle
End With
End With
I was able to use the following code to set the last cell of the second column equal to the sum of all of all cells of the second column.
Dim totals as Integer
For Each dr As DataRow In dt.Rows
totals += dr.Item(1)
Next
xlSheet.Range("B" & (lTotalRows + 1).ToString).Value = totals
If you know the number of total rows, you could insert the formula below into the cell at the bottom of the column. Your example data shows 16 rows, not including the top header row.