4

I have successfully created an Excel file using OLEDB (after first creating a table / sheet). I would like to insert a formula that sums a Cost (Currency) cell but have been unable find any techniques for doing so.

I have tried inserting the formula into the Cost field as follows but receive an invalid data type error, which is understandable:

cmd.Parameters.Add("P0", OleDbType.PropVariant).Value = "=SUM(K2:K5)"
cmd.CommandText = "INSERT INTO  [" & ExcelTableName & "] (Cost) VALUES(P0);"
cmd.ExecuteNonQuery()

Is there any way of doing this using OLEDB or will I need to use automation?

ron tornambe
  • 10,452
  • 7
  • 33
  • 60

1 Answers1

0

you could use a SQL Query that includes the formula in a column, and in Excel use an ADO DB Recordset to execute the query.

Then you would use the CopyFromRecordset method on the range object to dump your resultset into Excel which would include the formula.

FOR EXAMPLE:

sQry="Select fields, '=IF(A:A>=B:B, ''''Good'''', ''''Bad'''') from table where criteria'
xlApp.Range("A1").CopyFromRecordset oRs

this can also be done from .NET, just differently...

see MSDN Library: Transfer data to a worksheet by using ADO.NET

Our Man in Bananas
  • 5,809
  • 21
  • 91
  • 148