Calling Excel from a C# function

Discussion in 'Programming' started by nickjason, Jul 26, 2009.

  1. #1
    I need to know how to call an external Excel function from a class. The excel formula works fine inside the main function but not in the separate class.

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Excel;

    namespace TestNormSInv
    {
    public class optionMath
    {
    public double testDouble(double price)
    {
    double result = 0.0;
    //The line below produces the error !!!!!!!!!!!!!!!!!!!!!
    result = WorksheetFunction.NormSDist(price);
    return result;
    }

    public double testTriple(double price)
    {
    double result = 0.0;
    //The line below produces the error !!!!!!!!!!!!!!!!!!!!!
    result = WorksheetFunction.NormSDist(price);
    return result;
    }
    }
    class CalcExcel
    {
    static void Main(string[] args)
    {
    double result = 0.0;
    Excel.Application oXL;
    try {
    //Start Excel and get Application object.
    oXL = new Excel.Application();
    oXL.Visible = false;
    oXL.UserControl = false;

    // This code works
    result = oXL.WorksheetFunction.NormSDist(1.04);
    Console.WriteLine("Normsdist 1.04: {0}", result);
    optionMath OM = new optionMath();

    //This does not work
    result = OM.testDouble(1.04);
    }
    catch (SqlException e)
    {
    // Display error
    Console.WriteLine("Error: " + e);
    }
    finally {
    Console.WriteLine("Connection closed.");
    }
    }
    }
    }
     
    nickjason, Jul 26, 2009 IP