I've added the Excel formula into the text file (saved as a ".csv") and it gets converted when Excel opens it.
The code I used follows, in case it helps anyone....
I wanted to make this routine generic but I can't guarantee, as in this case, that the recordset fields are in the right order.
Public Sub CreateAgedDebtCSV(ByVal rsReportRecordset As ADODB.Recordset)
Dim objFSO As FileSystemObject
Dim objTextstream As TextStream
Dim intFinalRow As Integer
Dim strName As String
Dim strAddress As String
'Instantiate file and textstream objects to create/overwrite .csv file
Set objFSO = New FileSystemObject
Set objTextstream = objFSO.OpenTextFile(gsDatabaselocation & AGED_DEBT_CSV_FILE, ForWriting, True)
'Set initial line value for SUMming function
intFinalRow = 3
'Set up title and headings for .csv file
objTextstream.WriteLine ",,,,Financial Aged Debt Report,,,,,,"
objTextstream.WriteBlankLines 1
objTextstream.WriteLine "Client Name,Client ID,Address,Phone,Last Payment,Current,30+ Days," & _
"60+ Days,90+ Days,120+ Days,Total"
'Loop through report recordset
With rsReportRecordset
.MoveFirst
Do Until .EOF
'Ensure names and addresses do not have commas within them, as this will throw the layout of the .csv
strName = Replace(.Fields(1).Value, ",", " ", 1)
strAddress = Replace(.Fields(11).Value, ",", " ", 1)
'Write line to .csv file for each record in recordset
objTextstream.WriteLine strName & "," & .Fields(0).Value & "," & strAddress & "," & _
.Fields(12).Value & "," & .Fields(10).Value & "," & .Fields(4).Value & "," & _
.Fields(5).Value & "," & .Fields(6).Value & "," & .Fields(7).Value & "," & _
.Fields(8).Value & "," & .Fields(9).Value
'Increment row count for SUMming function
intFinalRow = intFinalRow + 1
.MoveNext
Loop
End With
'Create totals line
objTextstream.WriteBlankLines 1
objTextstream.WriteLine ",,,,Totals :,=SUM(F4:F" & CStr(intFinalRow) & "),=SUM(G4:G" & CStr(intFinalRow) & ")," & _
"=SUM(H4:H" & CStr(intFinalRow) & "),=SUM(I4:I" & CStr(intFinalRow) & ")," & _
"=SUM(J4:J" & CStr(intFinalRow) & "),=SUM(K4:K" & CStr(intFinalRow) & ")"
objTextstream.Close
Set objTextstream = Nothing
Set objFSO = Nothing
End Sub