<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Excel Archives - CenterSpace</title>
	<atom:link href="https://www.centerspace.net/tag/excel/feed" rel="self" type="application/rss+xml" />
	<link>https://www.centerspace.net/tag/excel</link>
	<description>.NET numerical class libraries</description>
	<lastBuildDate>Tue, 07 Feb 2023 21:26:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>
<site xmlns="com-wordpress:feed-additions:1">104092929</site>	<item>
		<title>Calling External .NET Libraries from Excel</title>
		<link>https://www.centerspace.net/calling-external-net-libraries-from-excel</link>
					<comments>https://www.centerspace.net/calling-external-net-libraries-from-excel#comments</comments>
		
		<dc:creator><![CDATA[CenterSpace]]></dc:creator>
		<pubDate>Thu, 09 Dec 2010 06:10:05 +0000</pubDate>
				<category><![CDATA[Excel]]></category>
		<category><![CDATA[Marketing]]></category>
		<category><![CDATA[NMath Stats Tutorial]]></category>
		<category><![CDATA[NMath Tutorial]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[excel interop]]></category>
		<category><![CDATA[NMath and Excel]]></category>
		<guid isPermaLink="false">http://www.centerspace.net/blog/?p=2845</guid>

					<description><![CDATA[<p>There are many circumstances where you may need to access an external library of functions or routines from Excel.  For example, if you need a complex function such as fitting data to a surface, or portfolio optimization, that is not natively available in Excel.  There also may be a need to protect proprietary calculations by [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/calling-external-net-libraries-from-excel">Calling External .NET Libraries from Excel</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>There are many circumstances where you may need to access an external library of functions or routines from Excel.  For example, if you need a complex function such as fitting data to a surface, or portfolio optimization, that is not natively available in Excel.  There also may be a need to protect proprietary calculations by using user defined functions to process algorithms in a black box manner.  I was looking for a way to rapidly prototype some calculations without setting up a complex development environment.</p>
<p>Harking back to the old rule of development projects of  “two out of three”, when the three metrics are fast, cheap, and quality.  On any time limited project you only can plan to achieve two metrics, never all three. Initially I like to dive in and start with fast and cheap and work my way towards quality as necessary.  So, we&#8217;ll start with the quick and dirty approach to calling external libraries from Excel.</p>
<h3>Project Setup</h3>
<p>You must have a version of .NET Framework of 2.0 or greater.  The latest .NET version is free and easily downloaded from Microsoft.</p>
<p>You&#8217;ll also need:</p>
<ul>
<li>Excel 97 or later.</li>
<li>External library assemblies that you need to access from Excel. In our case we will use Centerspace’s <strong>NMath.dll</strong> and <strong>NMathStats.dll</strong>.</li>
<li>A freeware product called ExcelDNA written by Govert van Drimmelen that can be downloaded at <a href="https://excel-dna.net/">Excel-DNA</a> .</li>
</ul>
<p>The first order of business is to unpack the downloaded file, <strong>ExcelDNA.zip</strong>, into a working directory.  For our example, we will use <em>CenterSpaceExcel</em> as our directory name. After unpacking you should have two folders <em>Distribution</em> and <em>Source</em> in our <em>CenterSpaceExcel</em> directory.  Inside the <em>Distribution</em> folder locate the file <strong>ExcelDNA.xll</strong> and rename it to <strong>NMathExcel.xll</strong>.</p>
<p>We now need to locate in the same directory the file <strong>ExcelDna.dna</strong> and rename it to <strong>NMathExcel.dna</strong>.  Then using notepad, or your favorite code editor, and open the file <strong>NMathExcel.dna</strong>.</p>
<p>You should see the following code:</p>
<pre lang="vb">
<DnaLibrary>
<![CDATA[ 
     Public Module Module1   
       Function AddThem(x, y)      
          AddThem = x + y   
       End Function 
    End Module 
]]&gt;
</DnaLibrary></pre>
<div  mce_tmp="1">Assuming CenterSpace NMath and NStat are installed in the standard locations. Change it to read as follows and save:</div>
<pre lang="vb">
<DnaLibrary>

<Reference Name="CenterSpace.NMath.Core" />
<Reference Path="C:\Program Files\CenterSpace\NMath 4.1\Assemblies\NMath.dll" />
<Reference Name="CenterSpace.NMath.Stats" />
<Reference Path="C:\Program Files\CenterSpace\NMath Stats 3.2\Assemblies\NMathStats.dll" />

<![CDATA[
	Imports NMath = CenterSpace.NMath.Core
	Imports Stats = CenterSpace.NMath.Stats

	Public Module NMathExcel

		<ExcelFunction(Description:="Returns x to the y power")> _
	    	Function NPower(x as double, y As double) As double
			NPower = NMath.NMathFunctions.PowFunction(x, y)
		End Function

		<ExcelFunction(IsMacroType:=True, IsVolatile:=True)> _
		Function NRand() As double
			dim rand As New NMath.RandGenMTwist
			NRand = rand.Next53BitRes()
		End Function

		<ExcelFunction(Description:="Binomial Distribution: Number of Successes, Trials, Probability, Cumulative is True or False")> _
		Function NBinomDist(NSuccess As Int32, NTrials As Int32, Prob As double, Cumul As Boolean) As double
			dim nbin As New Stats.BinomialDistribution
			nbin.N = NTrials
			nbin.P = Prob
			IF Cumul
				NBinomDist = nbin.CDF(NSuccess)
			Else
				NBinomDist = nbin.PDF(NSuccess)
			End If
		End Function

		Function NDoubleMatrixRand(rsize As integer, csize As integer, RandLBx As integer, RandUBy As integer) As Object(,)
			dim rng As New NMath.RandGenUniform(RandLBx,RandUBy)
			Rng.Reset(&#038;H124)
			dim TempA As New NMath.DoubleMatrix(rsize, csize, Rng)
			NDoubleMatrixRand = NCopyArray(TempA, rsize, csize)

		End Function

		Function NCopyArray(IMatrix As Object, rsize As integer, csize As integer) As Object(,)
			dim i As Integer
			dim j As Integer
			dim OArray(rsize, csize) As Object
			for i = 0 to rsize - 1
			   for j = 0 to csize - 1
				OArray(i,j) = IMatrix(i,j)
			   next j
			next i
			NCopyArray = OArray
		End Function		

	End Module
]]&gt;</pre>
<p>We now have created the VB code to call our CenterSpace Math and Statistics libraries with the following five functions.</p>
<ol>
<li>The first function shows a simple math library call to the Power function which takes a number x and raises it to the y power and returns the value.</li>
<li>The second function shows a call to obtain a fast random number from the math library.  Since we want a new number each time the spreadsheet is re-calculated we have made the function <code>volatile</code>.</li>
<li>The third function call shows how to set values that need to be accessed by a function in our .NET assemble; in this case, the Binomial Distribution.</li>
<li>The fourth function demonstrates the creation of a <code>DoubleMatrix</code> that is the filled with random uniformly distributed numbers.</li>
<li>The fifth function is a helper sub-routine to transfer data across the com interface.</li>
</ol>
<h3>Test our setup in Excel</h3>
<p>Open Excel and move your cursor the <span style="text-decoration: underline;">Tools</span> menu item.  Usually towards the bottom of the drop down menu you will find the selection <span style="text-decoration: underline;">Add-Ins</span>.  After selecting <span style="text-decoration: underline;">Add-Ins</span>, you see the pop-up window with the option to select Microsoft supplied Add-ins.  Choose the <span style="text-decoration: underline;">Browse</span> option and go to the working directory we created at the beginning.  In our case, this will be the <em>CenterSpaceExcel</em> directory.  Next select the <em>Distribution</em> folder and you should see the renamed file: <strong>NMathExcel.xll</strong>.  Select it and you should now see the following screen.</p>
<figure id="attachment_2899" aria-describedby="caption-attachment-2899" style="width: 360px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/ExcelAddin1.gif"><img decoding="async" class="size-full wp-image-2899" title="ExcelAddin" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/ExcelAddin1.gif" alt="" width="360" height="422" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/ExcelAddin1.gif 360w, https://www.centerspace.net/wp-content/uploads/2010/12/ExcelAddin1-255x300.gif 255w" sizes="(max-width: 360px) 100vw, 360px" /></a><figcaption id="caption-attachment-2899" class="wp-caption-text">Selecting a user created XLL as an Add-in for Excel</figcaption></figure>
<p>Make sure NMathExcel is checked and click OK. If you get an error and this point it is probably due to a typo in the DNA file, otherwise you will get the expected new sheet ready for entry.</p>
<p>Select an empty cell and then select from the menu bar <span style="text-decoration: underline;">Insert</span> then from the pulldown <span style="text-decoration: underline;">Function</span>.  You should see the following pop-up.</p>
<figure id="attachment_2902" aria-describedby="caption-attachment-2902" style="width: 540px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsertFunction.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2902" title="InsertFunction" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsertFunction.gif" alt="" width="540" height="423" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsertFunction.gif 540w, https://www.centerspace.net/wp-content/uploads/2010/12/InsertFunction-300x235.gif 300w" sizes="(max-width: 540px) 100vw, 540px" /></a><figcaption id="caption-attachment-2902" class="wp-caption-text">Selecting the category containing our NMath functions</figcaption></figure>
<p>At the bottom of the category pull down you should see our NMathExcel Functions;  Select it and you should have these options.:</p>
<figure id="attachment_2905" aria-describedby="caption-attachment-2905" style="width: 540px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsNMathFctn.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2905" title="InsNMathFctn" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsNMathFctn.gif" alt="" width="540" height="427" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsNMathFctn.gif 540w, https://www.centerspace.net/wp-content/uploads/2010/12/InsNMathFctn-300x237.gif 300w" sizes="(max-width: 540px) 100vw, 540px" /></a><figcaption id="caption-attachment-2905" class="wp-caption-text">NMath Excel Function Category</figcaption></figure>
<p>If we choose <code>NPower</code>, we will get the next screen,</p>
<figure id="attachment_2906" aria-describedby="caption-attachment-2906" style="width: 540px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsNMathFctnPwrArg.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2906" title="InsNMathFctnPwrArg" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsNMathFctnPwrArg.gif" alt="" width="540" height="359" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsNMathFctnPwrArg.gif 540w, https://www.centerspace.net/wp-content/uploads/2010/12/InsNMathFctnPwrArg-300x199.gif 300w" sizes="(max-width: 540px) 100vw, 540px" /></a><figcaption id="caption-attachment-2906" class="wp-caption-text">Calling NMath Library Power function in Excel</figcaption></figure>
<p>I arbitrarily typed the value of 3.2 for x and 3.327 for y.  You can see the result of 47.9329301 before selecting OK.</p>
<p>Select OK and Excel will insert the value into the cell.  Select another blank cell and this time choose our <code>NRand()</code> function.  You will notice there is no opportunity to enter values and finish by selecting OK.  At this point you should see a number between 0 and 1 in the cell.  Each time you press F9 (sheet recalc) a new random number will appear.  If we had not made this function volatile the number would not change unless you edit the cell.</p>
<p>To test our Binomial Distribution function, again we will select a new cell and use the insert function option to insert the <code>NBinomDist</code> function with the following values.</p>
<figure id="attachment_2909" aria-describedby="caption-attachment-2909" style="width: 540px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsNMathFctnBinomArg.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2909" title="InsNMathFctnBinomArg" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsNMathFctnBinomArg.gif" alt="" width="540" height="361" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsNMathFctnBinomArg.gif 540w, https://www.centerspace.net/wp-content/uploads/2010/12/InsNMathFctnBinomArg-300x200.gif 300w" sizes="(max-width: 540px) 100vw, 540px" /></a><figcaption id="caption-attachment-2909" class="wp-caption-text">Calling NMath Statistical function Binomial Distribution from Excel</figcaption></figure>
<p>At this point we have made successful calls into both of CenterSpace&#8217;s NMath and NMath Stats .NET math libraries.</p>
<p>In our fourth example, we will see how Excel handles matrices and look at issues passing array arguments across the COM interface.  Excel 2003 was limited to a maximum of 60,000 cells in an array, but Excel 2007 was expanded to handle 2 million.  Excel has some quirky ways of displaying matrices, and I&#8217;ll cover the in&#8217;s and out&#8217;s of these quirks.</p>
<p>We have written the basic code to set up a function called <code>NDoubleMatrixRand</code> for the purpose of creating a matrix with supplied dimensions and filled with uniform Random numbers over a specified distribution.  We will select another blank cell and again go to insert function and this time choose <code>NDoubleMatrixRand</code>.  Suppose we want to create a 6&#215;6 matrix filled with random numbers between -2 and 2.  Our input will look like the following screen.</p>
<figure id="attachment_2910" aria-describedby="caption-attachment-2910" style="width: 600px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsDblMtrxRandArg.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2910" title="InsDblMtrxRandArg" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsDblMtrxRandArg.gif" alt="" width="600" height="421" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsDblMtrxRandArg.gif 600w, https://www.centerspace.net/wp-content/uploads/2010/12/InsDblMtrxRandArg-300x210.gif 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption id="caption-attachment-2910" class="wp-caption-text">Creating a DoubleMatrix in Excel using NMath</figcaption></figure>
<p>Notice the equal sign in the middle right of the above screen is equal to {-0.994818527251482,-0.08</p>
<p>Values inclosed in curly brackets that are separated by commas indicates that an matrix was actually created, but you can see the Formula result is only displaying a partial value due to display size. At this point when you select OK, you will have a cell with a single value.  Here is where the fun begins.  Start at the cell and drag a 6&#215;6 range as shown in the following screen.</p>
<figure id="attachment_2911" aria-describedby="caption-attachment-2911" style="width: 564px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsDblMtrxRandDsply.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2911" title="InsDblMtrxRandDsply" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsDblMtrxRandDsply.gif" alt="" width="564" height="274" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsDblMtrxRandDsply.gif 564w, https://www.centerspace.net/wp-content/uploads/2010/12/InsDblMtrxRandDsply-300x145.gif 300w" sizes="(max-width: 564px) 100vw, 564px" /></a><figcaption id="caption-attachment-2911" class="wp-caption-text">Selecting the area the matrix is to be displayed in</figcaption></figure>
<p>Now get your fingers limbered. Here is where it gets a bit obscure &#8211; do exactly as follows.</p>
<ul>
<li>Press the F2 key.  (<em>pressing F2 may be  optional but is recommended by Excel as the cell leaves the edit mode</em>)</li>
<li>Press and hold the Ctrl key followed by</li>
<li>pressing and holding the Shift key followed by</li>
<li>pressing the Enter key</li>
</ul>
<p>and presto chango!  You should see a screen like this.</p>
<figure id="attachment_2913" aria-describedby="caption-attachment-2913" style="width: 561px" class="wp-caption alignnone"><a href="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsDblMtrxRandDsplyRslt.gif"><img decoding="async" loading="lazy" class="size-full wp-image-2913" title="InsDblMtrxRandDsplyRslt" src="https://www.centerspace.net/blog/wp-content/uploads/2010/12/InsDblMtrxRandDsplyRslt.gif" alt="" width="561" height="211" srcset="https://www.centerspace.net/wp-content/uploads/2010/12/InsDblMtrxRandDsplyRslt.gif 561w, https://www.centerspace.net/wp-content/uploads/2010/12/InsDblMtrxRandDsplyRslt-300x112.gif 300w" sizes="(max-width: 561px) 100vw, 561px" /></a><figcaption id="caption-attachment-2913" class="wp-caption-text">Displaying a Matrix in Excel </figcaption></figure>
<p>Notice that your cell&#8217;s formula is now enclosed in { }, indicating to Excel that the contained formula is an array function.  This is the only way to get matrices displayed.  Also, if you try to edit this cell you will get an error that changes are not allowed.  If  you want to change the dimensions simply reference the values from another cell when you create the function.</p>
<p>The fifth function <code>NCopyArray</code> copies the library matrix across the COM bridge into an Excel array object.  As I stated in the beginning this would be a quick and dirty approach and would leave room for improvement.</p>
<h3>Summary</h3>
<p>In my next post, I will provide the above code in C# and add more function calls with some matrices with hopefully an improved approach to <code>NCopyArray</code>.  Future posts will include creating a packaged XLL and a more complex example such as curve fitting.</p>
<p>Since time is our most precious asset, being able to quickly access complex math functions with a general purpose tool like Excel should save time and money!</p>
<p>At CenterSpace, we are interested if this blog is helpful and if there is a need for more examples of how our libraries can be accessed by Excel.  Let us know what areas are of interest to you.</p>
<p>Mike  Magee</p>
<p><strong>Thanks and Resources </strong><br />
Also, a special thanks to Govert van Drimmelen for writing a wonderful tool such as ExcelDNA.</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/calling-external-net-libraries-from-excel">Calling External .NET Libraries from Excel</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.centerspace.net/calling-external-net-libraries-from-excel/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2845</post-id>	</item>
	</channel>
</rss>
