Quantcast
Channel: Excel-DNA
Viewing all 24 articles
Browse latest View live

Excel-DNA version 0.29 – RC available

$
0
0

I have posted a release candidate of Excel-DNA version 0.29 to the CodePlex site. The download is available at http://exceldna.codeplex.com/releases/view/66405. I will wait a week or two for some confirmation that this version works correctly before setting this release to ‘recommended’ status and updating the NuGet package. Any results from your testing with this version would be very helpful.

Excel-DNA version 0.29 adds support for a number of specialized Excel features. The 64-bit version of Excel 2010 is fully supported, registration-free Custom Task Panes can be created under Excel 2007 and later, direct COM server integration can improve integration with legacy VBA code, and macros with parameters are registered. In addition, there are some features to improve the development and debugging workflow, and a few minor bugfixes. The complete change list is included below.

More information about the new features will be posted on the Excel-DNA website in the coming weeks. Any comments or questions are welcome on the Google group – http://groups.google.com/group/exceldna – or by contacting me directly.

As always, I greatly appreciate any feedback on this version, and on Excel-DNA in general.

-Govert

Complete change list

  • BREAKING CHANGE! Changed SheetId in the ExcelReference type to an IntPtr for 64-bit compatibility.
  • Changed initialization – only create sandboxed AppDomain under .NET 4 (or if explicitly requested with CreateSandboxedAppDomain=’true’ attribute on DnaLibrary tag in .dna file).
  • Fixed memory leak when getting SheetId for ExcelReference parameters.
  • Fixed Ribbon RunTagMacro when no Workbook open.
  • Added support for the 64-bit version of Excel 2010 with the .Net 4 runtime.
  • Added Cluster-safe function support for Excel 2010 HPC Cluster Connector – mark functions as IsClusterSafe=true.
  • Added CustomTaskPane support and sample.
  • Added COM server support for RTD servers and other ComVisible classes. Mark ExternalLibraries and Projects as ComServer=”true” in the .dna file. Supports Regsvr32 registration or by calling ComServer.DllRegisterServer. Allows direct RTD and VBA object instantiation. Includes TypeLib registration and packing support.
  • Added support for macros with parameters.
  • Added ArrayResizer sample.
  • Added C# 4 dynamic type sample.
  • Added Path attribute to SourceItem tag to allow external source.
  • Added LoadFromBytes attribute to ExternalLibrary tag to prevent locking of .dll.
  • Added /O output path option to ExcelDnaPack.
  • Added ‘before’ option to CommandBars xml.
  • Added Int64 support for parameters and return values.

Excel VBA to VB.NET with Excel-DNA and NetOffice

$
0
0

Excel-DNA is a great library to help ease the path from Excel VBA to VB.NET. Last year another part of the puzzle fell in place: I discovered NetOffice, a version-independent set of Office interop assemblies put together by Sebastian Lange. By referencing the NetOffice assemblies instead of the official Primary Interop Assemblies (PIA) for Office, an Excel-DNA add-in can target various Excel versions with a single add-in, and also ease distribution of the required interop assemblies, even packing them into the .xll add-in itself.

To explore how Excel-DNA and NetOffice can combine to convert a VBA add-in to VB.NET, I picked a small add-in made by Robert del Vicario that does a risk analysis simulation inspired by the Pallisade @RISK add-in. I took Robert’s original RiskGen VBA add-in , and created a new Excel-DNA add-in in VB.NET (I used Visual Studio, but the free SharpDevelop IDE should work fine too). I documented the steps along the way of creating the VB.NET project, making an add-in based on Excel-DNA and using NetOffice to help port the VBA code to VB.NET. The resulting document (RiskGen Port Log.docx) outlining exactly how I ported the add-in, with the new VB.NET-based  RiskGen.NET is also on Robert’s site.

I’m also looking for some more examples of free/open source VBA add-ins to port to Excel-DNA. The best add-ins will contain a mix of user-defined functions and macros which use the Excel object model. Please post to the Google group or mail me directly if you have any suggestions.

And as always, if you need any support porting your Excel VBA add-ins to .NET using Excel-DNA, I’m happy to help on the Excel-DNA Google group.

Patrick O’Beirne’s guide for Excel VBA to VB.NET migration

Excel-DNA Version 0.30 Released

$
0
0

Excel-DNA Version 0.30 has now been released on CodePlex. The download
is available from http://exceldna.codeplex.com/releases/view/95861.

This version implements support for RTD-based asynchronous worksheet
functions based on a thread-safe RTD base class – ExcelRtdServer. The
asynchronous support is designed to (optionally) integrate with
the .NET 4.0 Task-based operations, as well as the Reactive Extensions
library, allowing IObservables to be exposed as ‘live’ worksheet UDFs
- (thus ‘RxExcel’). The language-specific support for asynchronous
functions found in C# 5, Visual Basic 11 and F# 2.0 can be easily
integrated with the Excel-DNA asynchronous interfaces. Some examples
experimenting with the new async features are available in the
download.

Various bug fixes have also accumulated over the last 18 months, and
are collected in this release.

As always, I greatly appreciate any feedback on this version, and on
Excel-DNA in general. Any comments or questions are welcome on the
Google group or by contacting me directly.

Changelist – Version 0.30 (12 December 2012)

* Fixed LoadComAddIn error when using a direct ExcelComAddIn-derived
class.
* Fixed (Ribbon Helper) display in ribbon tooltips.
* Fixed RTD / array formula activation bug.
* Fixed IsMacroType=true reference argument sheet error
(ExcelReference pointed to active sheet instead of current sheet).
* Fixed array marshaling pointer manipulation concern under 64-bit
Excel.
* Fixed check for derived attributes too – for backward compatibility
with v. 0.25.
* Fixed assembly multiple-loading problem for packed assemblies.
* Fixed persistent COM registration (Regsv32.exe /
ComServer.DllRegisterServer) to allow HKCR registration whenever
possible (for UAC elevation issue).
* Fixed Excel version check when COM / RTD Server loads before add-in
is loaded – ribbon would not load.
* Fixed IntPtr OverflowException in high-memory 32-bit processes.
* Fixed custom task panes UserControl activation – do HKCR
registration whenever possible (for UAC elevation issue).
* Fixed double[0,1] array marshaling memory allocation error with
potential access violation.
* Allow abstract base classes in ExcelRibbon class hierarchy. Now
loads the first concrete descendent of ExcelRibbon as the ribbon
handler.
* Remove Obsolete class ExcelDna.Integration.Excel. (Use ExcelDnaUtil
instead.) Allows smooth XlCall usage.
* Allow external SourceItem packing.
* Add ExcelAsyncUtil for async macro calls.
* Add thread-safe RTD server base class ExcelRtdServer.
* Add async function helper as ExcelAsyncUtil.Run.
* Add support for Reactive Extensions via RTD via
ExcelAsyncUtil.Observe and related interfaces.
* Change ExcelRibbon and ComAddIn loading to use declared ProgId and
Guid if _both_ attributes are present. Fixed Ribbon QAT issue.
* Revisit caching of Application object.
* Rename ExcelDna.Integration.Integration to
ExcelDna.Integration.ExcelIntegration.
* Implement macro shortcuts (from ExcelCommand attributes).
* Changed re-open via File->Open to do full AppDomain unload and add-
in reload.

Excel-DNA NuGet Package Updated

$
0
0

I’ve updated and improved the Excel-DNA NuGet package. (NuGet is the Visual Studio package manager that makes it easy to download and install external libraries into your projects.)

To turn your Class Library project into an Excel add-in, just open Tools -> Library Package Manager -> Package Manager Console, and enter

PM> Install-Package Excel-DNA

The Excel-DNA package now has an install script that creates the required .dna file, and a post-build step to copy the .xll and run the packing tool, and even configures debugging. The package should work for C#, Visual Basic and F# Class Library projects on:

  • Visual Studio 2010 Professional and higher
  • Visual Studio 2012 Professional and higher
  • Visual Studio 2012 Express for Windows Desktop

Please post any feedback – bugs, good or bad comments – to the Excel-DNA Google group.

Async and event-streaming Excel UDFs with F#

$
0
0

There have been a some recent posts mentioning the asynchronous and reactive programming features in F#. Since Excel-DNA 0.30 added support for creating async and IObservable-based real-time data functions, I’d like to show how these F# features can be nicely exposed to Excel via Excel-DNA.

IObservable to Excel via Excel-DNA

Excel-DNA 0.30 allows an add-in to expose IObservable sources to Excel as real-time data functions. (Actually Excel-DNA defines an interface called IExcelObservable that matches the semantics of IObservable<object> – this is because we still target .NET 2.0 with the core library.)

Asynchronous function can then be implemented as an IObservable that returns a single value before completing. Cancellation (triggered when the user removes a real-time or async formula) is supported via the standard IDisposable mechanism.

Internally, Excel-DNA implements a thread-safe RTD server and registers the IObservable as an RTD topic. So some aspects of the IObservable support are subject to Excel’s RTD feature works, for example the RTD throttle interval (by default 2 seconds) will also apply to IObservable functions.

The following functions in the ExcelDna.Integration.ExcelAsyncUtil helper class are relevant:

  • ExcelAsyncUtil.Initialize() – this should be called in a macro context before any of the other features are used, typically from the AutoOpen() handler.
  • ExcelAsyncUtil.Observe(...) – registers an IExcelObservable as a real-time data function with Excel. Subsequent OnNext() calls will raise updates via RTD.
  • ExcelAsyncUtil.Run(...) – a helper method that runs a function asynchronously on a .NET threadpool thread.

In addition, we’ll use

  • ExcelObservableSource – a delegate type for functions that return an IExcelObservable.

Some links:

F# helpers for async and IObservable-based events

To initialize the async support in Excel-DNA, we need some code like the following:

namespace FsAsync

open System
open System.Threading
open System.Net
open Microsoft.FSharp.Control.WebExtensions
open ExcelDna.Integration

/// This class implements the IExcelAddin which allows us to initialize the ExcelAsyncUtil support.
/// It must not be a nested class (e.g. defined as a type inside a module) but a top-level class (inside a namespace)
type FsAsyncAddIn () =
    interface IExcelAddIn with
        member this.AutoOpen ()  = 
            ExcelAsyncUtil.Initialize ()
        member this.AutoClose () = ExcelAsyncUtil.Uninitialize ()

    // define a regular Excel UDF just to show that the add-in works
    [<ExcelFunction(Description="A test function from F#")>]
    static member fsaAddThem (x:double) (y:double) = x + y

F# supports an asynchronous programming model via ‘async computation expressions’. The result of an async computation expression is a value of type Async<'T>, which we need to convert to an IExcelObservable. We use a standard CancellationTokenSource hooked up to the IDisposable to enable cancellation.

module FsAsyncUtil =

    /// A helper to pass an F# Async computation to Excel-DNA 
    let excelRunAsync functionName parameters async =
        let obsSource =
            ExcelObservableSource(
                fun () -> 
                { new IExcelObservable with
                    member __.Subscribe observer =
                        // make something like CancellationDisposable
                        let cts = new CancellationTokenSource ()
                        let disp = { new IDisposable with member __.Dispose () = cts.Cancel () }
                        // Start the async computation on this thread
                        Async.StartWithContinuations 
                            (   async, 
                                ( fun result -> 
                                    observer.OnNext(result)
                                    observer.OnCompleted () ),
                                ( fun ex -> observer.OnError ex ),
                                ( fun ex ->
                                    observer.OnCompleted () ),
                                cts.Token 
                            )
                        // return the disposable
                        disp
                }) 
        ExcelAsyncUtil.Observe (functionName, parameters, obsSource)

Another neat feature of F# is that events are first-class types that implement IObservable. This means any F# event can serve as a real-time data source in an Excel formula. To bridge the F# events to the IExcelObservable interface is really easy, we just have the following helper:

    /// A helper to pass an F# IObservable to Excel-DNA
    let excelObserve functionName parameters observable = 
        let obsSource =
            ExcelObservableSource(
                fun () -> 
                { new IExcelObservable with
                    member __.Subscribe observer =
                        // Subscribe to the F# observable
                        Observable.subscribe (fun value -> observer.OnNext (value)) observable
                })
        ExcelAsyncUtil.Observe (functionName, parameters, obsSource)

Sample functions

Given the above helpers, we can now explore a few ways to implement async and real-time streaming functions. As examples:

Here is a plain synchronous function to download a url into a string:

let downloadString url = 
    try
        let uri = new System.Uri(url)
        let webClient = new WebClient()
        let html = webClient.DownloadString(uri)
        html
    with
        | ex -> "!!!ERROR: " + ex.Message
  • Async implementation 1: Use Excel-DNA async directly to run downloadString on a ThreadPool thread
    let downloadStringAsyncRunTP1 url = 
        ExcelAsyncUtil.Run ("downloadStringAsyncTP1", url, (fun () -> downloadString url :> obj))
    

Create an F# asynchronous computation for the download (this functions is not exported to Excel)

let downloadStringAsyncImpl url = async {
    try

        // In here we could check for cancellation using 
        // let! ct = Async.CancellationToken
        // if ct.IsCancellationRequested then ...
        let uri = new System.Uri(url)
        let webClient = new WebClient()
        let! html = webClient.AsyncDownloadString(uri)
        return html
    with
        | ex -> return "!!!ERROR: " + ex.Message 
    }
  • Async implementation 2: This function runs the async computation synchronously on a ThreadPool thread because that’s what ExcelAsyncUtil.Run does. Blocking calls will block a ThreadPool thread, eventually limiting the concurrency of the async calls
    let downloadStringAsyncTP2 url = 
        ExcelAsyncUtil.Run ("downloadStringAsyncTP2", url, (fun () -> Async.RunSynchronously (downloadStringAsyncImpl url) :> obj))
    
  • Async implementation 3: Use the helper we defined above. This runs the async computation using true F# async. Should not block ThreadPool threads, and allows cancellation
    let downloadStringAsync url = 
        FsAsyncUtil.excelRunAsync "downloadStringAsync" url (downloadStringAsyncImpl url)
    

Helper that will create a timer that ticks at timerInterval for timerDuration, and is then done. Also not exported to Excel (incompatible signature). Notive that the from F#, the timer.Elapsed event of the BCL Timer class implements IObservable, so can be used directly with the transformations in the F# Observable module.

let createTimer timerInterval timerDuration =
    // setup a timer
    let timer = new System.Timers.Timer(float timerInterval)
    timer.AutoReset <- true
    // return an async task for stopping it after the duration
    let timerStop = async {
        timer.Start()
        do! Async.Sleep timerDuration
        timer.Stop() 
        }
    Async.Start timerStop
    // Make sure that the type we actually observe in the event is supported by Excel
    // by converting the events to timestamps
    timer.Elapsed |> Observable.map (fun elapsed -> DateTime.Now) 
  • Event implementation: Finally this is the Excel function that will tick away in a cell. Entered into a cell (and formatted as a Time value), the formula =startTimer(5000, 60000) will show a clock that ticks every 5 seconds for a minute.
    let startTimer timerInterval timerDuration =
        FsAsyncUtil.excelObserve "startTimer" [|float timerInterval; float timerDuration|] (createTimer timerInterval timerDuration)
    

Putting everything together in an Excel add-in

A complete .dna script file with the above code can be found in the Excel-DNA distribution, under Distribution\Samples\Async\FsAsync.dna.

Alternatively, the following steps would build an add-in in Visual Studio:

  • Create a new F# library in Visual Studio.
  • Install the Excel-DNA package from NuGet (Install-Package Excel-DNA from the NuGet console).
  • Set up the Debug path:
    1. Select “Start External Program” and browse to find Excel.exe, e.g. for Excel 2010 the path might be: C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE.
    2. Enter the full path to the .xll file in the output as the Command line arguments,
      e.g. C:\MyProjects\TestDnaFs\bin\Debug\TestDnaFs-addin.xll.
  • Place the following code in Library1.fs, compile and run:
    
    namespace FsAsync
    
    open System
    open System.Threading
    open System.Net
    open Microsoft.FSharp.Control.WebExtensions
    open ExcelDna.Integration
    
    /// This class implements the IExcelAddin which allows us to initialize the ExcelAsyncUtil support.
    /// It must not be a nested class (e.g. defined as a type inside a module) but a top-level class (inside a namespace)
    type FsAsyncAddIn () =
        interface IExcelAddIn with
            member this.AutoOpen ()  = 
                ExcelAsyncUtil.Initialize ()
            member this.AutoClose () = ExcelAsyncUtil.Uninitialize ()
    
        // a regular Excel UDF just to show that the add-in works
        static member fsaAddThem (x:double) (y:double) = x + y
    
    /// Some utility functions for connecting Excel-DNA async with F#
    module FsAsyncUtil =
        /// A helper to pass an F# Async computation to Excel-DNA 
        let excelRunAsync functionName parameters async =
            let obsSource =
                ExcelObservableSource(
                    fun () -> 
                    { new IExcelObservable with
                        member __.Subscribe observer =
                            // make something like CancellationDisposable
                            let cts = new CancellationTokenSource ()
                            let disp = { new IDisposable with member __.Dispose () = cts.Cancel () }
                            // Start the async computation on this thread
                            Async.StartWithContinuations 
                                (   async, 
                                    ( fun result -> 
                                        observer.OnNext(result)
                                        observer.OnCompleted () ),
                                    ( fun ex -> observer.OnError ex ),
                                    ( fun ex ->
                                        observer.OnCompleted () ),
                                    cts.Token 
                                )
                            // return the disposable
                            disp
                    }) 
            ExcelAsyncUtil.Observe (functionName, parameters, obsSource)
    
        /// A helper to pass an F# IObservable to Excel-DNA
        let excelObserve functionName parameters observable = 
            let obsSource =
                ExcelObservableSource(
                    fun () -> 
                    { new IExcelObservable with
                        member __.Subscribe observer =
                            // Subscribe to the F# observable
                            Observable.subscribe (fun value -> observer.OnNext (value)) observable
                    })
            ExcelAsyncUtil.Observe (functionName, parameters, obsSource)
    
    // Some test functions
    module TestFunctions =
        /// Plain synchronous download function
        /// can be called from Excel
        let downloadString url = 
            try
                let uri = new System.Uri(url)
                let webClient = new WebClient()
                let html = webClient.DownloadString(uri)
                html
            with
                | ex -> "!!!ERROR: " + ex.Message
    
        /// Uses Excel-DNA async to run download on a ThreadPool thread
        let downloadStringAsyncTP1 url = 
            ExcelAsyncUtil.Run ("downloadStringAsyncTP1", url, (fun () -> downloadString url :> obj))
    
        /// Create an F# asynchronous computation for the download
        /// Not exported to Excel
        let downloadStringAsyncImpl url = async {
            try
    
                // In here we could check for cancellation using 
                // let! ct = Async.CancellationToken
                // if ct.IsCancellationRequested then ...
                let uri = new System.Uri(url)
                let webClient = new WebClient()
                let! html = webClient.AsyncDownloadString(uri)
                return html
            with
                | ex -> return "!!!ERROR: " + ex.Message 
            }
    
        /// This function runs the async computation synchronously on a ThreadPool thread
        /// because that's what ExcelAsyncUtil.Run does
        /// Blocking calls will block a ThreadPool thread, eventually limiting the concurrency of the async calls
        let downloadStringAsyncTP2 url = 
            ExcelAsyncUtil.Run ("downloadStringAsyncTP2", url, (fun () -> Async.RunSynchronously (downloadStringAsyncImpl url) :> obj))
    
        /// This runs the async computation using true F# async
        /// Should not block ThreadPool threads, and allows cancellation
        let downloadStringAsync url = 
            FsAsyncUtil.excelRunAsync "downloadStringAsync" url (downloadStringAsyncImpl url)
    
        // Helper that will create a timer that ticks at timerInterval for timerDuration, then stops
        // Not exported to Excel (incompatible type)
        let createTimer timerInterval timerDuration =
            // setup a timer
            let timer = new System.Timers.Timer(float timerInterval)
            timer.AutoReset  Observable.map (fun elapsed -> DateTime.Now) 
    
        // Excel function to start the timer - using the fact that F# events implement IObservable
        let startTimer timerInterval timerDuration =
            FsAsyncUtil.excelObserve "startTimer" [|float timerInterval; float timerDuration|] (createTimer timerInterval timerDuration)
    

Support and feedback

The best place to ask any questions related to Excel-DNA is the Excel-DNA Google group. Any feedback from F# users trying out Excel-DNA or the features discussed here will be very welcome. I can also be contacted directly at govert@icon.co.za.

Caching and Asynchronous Excel UDFs

$
0
0

This sample shows how the result of an Excel-DNA async UDF call can be cached using the .NET 4 MemoryCache class.

<DnaLibrary Name="CachedAsyncSample" RuntimeVersion="v4.0" Language="C#">

<Reference Name="System.Runtime.Caching" />
<![CDATA[
using System;
using System.Threading;
using System.Runtime.Caching;
using ExcelDna.Integration;

public static class dnaFunctions
{
    public static object dnaCachedAsync(string input)
    {
        // First check the cache, and return immediately 
        // if we found something.
        // (We also need a unique key to identify the cache item)
        string key = "dnaCachedAsync:" + input;
        ObjectCache cache = MemoryCache.Default; 
        string cachedItem = cache[key] as string;
        if (cachedItem != null) 
            return cachedItem;

        // Not in the cache - make the async call 
        // to retrieve the item. (The second parameter here should identify 
        // the function call, so would usually be an array of the input parameters, 
        // but here we have the identifying key already.)
        object asyncResult = ExcelAsyncUtil.Run("dnaCachedAsync", key, () => 
        {
            // Here we fetch the data from far away....
            // This code will run on a ThreadPool thread.

            // To simulate a slow calculation or web service call,
            // Just sleep for a few seconds...
            Thread.Sleep(5000);

            // Then return the result
            return "The calculation with input " 
                    + input + " completed at " 
                    + DateTime.Now.ToString("HH:mm:ss");
        });

        // Check the asyncResult to see if we're still busy
        if (asyncResult.Equals(ExcelError.ExcelErrorNA))
            return "!!! Fetching data";

        // OK, we actually got the result this time.
        // Add to the cache and return
        // (keeping the cached entry valid for 1 minute)
        // Note that the function won't recalc automatically after 
        //    the cache expires. For this we need to go the 
        //    RxExcel route with an IObservable.
        cache.Add(key, asyncResult, DateTime.Now.AddMinutes(1), null);
        return asyncResult;
    }

    public static string dnaTest()
    {
        return "Hello from CachedAsyncSample";
    }
}

public class AddIn : IExcelAddIn
{
    public void AutoOpen() { ExcelAsyncUtil.Initialize(); }
    public void AutoClose() { ExcelAsyncUtil.Uninitialize(); }
}

]]>
</DnaLibrary>

F# and R in Excel

$
0
0

Natallie Baikevich has posted some very pretty examples of using F# with Excel-DNA. One function uses the R type provider to easily expose a feature from an R package as an UDF in Excel. Have a look at the write-up, and the code on GitHub.


Streaming real-time data to Excel

$
0
0

Gert-Jan van der Kamp has posted a very nice end-to-end example on CodeProject, showing how to create a WCF service and Excel-DNA add-in to stream real-time data into Excel.

The example uses to use the Reactive Extensions support in Excel-DNA v. 0.30 to push the data to an Excel UDF (using Excel’s RTD mechanism behind the scenes), together with a Duplex WCF service providing the data.

There was also this CodePlex discussion about the Excel ThrottleInterval option, which trades off the real-time update frequency against stability of the Excel calculation.

Getting started with F# and Excel-DNA in finance

$
0
0

Bram Jochems has written a friendly  ‘Getting Started’ post, discussing how to use F# with Excel-DNA in a finance context. His add-in with various F# / Excel-DNA helper utilities, and a bunch of quantitative finance-related UDFs, including option pricing function and volatility interpolation, has been published as a project on GithHub.

It’s well worth a look, whether you are using F# and keen to explore Excel-DNA, or just curious about F# and looking for some practical examples.

Excel-DNA 0.32 Release Candidate

$
0
0

I have posted to CodePlex (https://exceldna.codeplex.com/releases/view/119190) and the NuGet package manager (https://www.nuget.org/packages/Excel-DNA/0.32.0-rc1) a release candidate of the next Excel-DNA version.
I hope to make a final release in the next few weeks, once I’ve had confirmation that this version works well on the various platforms and Excel versions.

Please test, and let me know of any problems or surprises you run into, or confirm what features, platforms and Excel versions work correctly.
The CodePlex download is structured as before, and for the NuGet package manager, you can upgrade to the pre-release version with:
    PM> Upgrade-Package Excel-DNA -Pre

——————————————-

Excel-DNA 0.32 consolidates a large number of bug fixes and improvements that have accumulated over the last year. In particular, a number of edge cases that affect Excel-DNA add-ins under Excel 2013 have been addressed.

Native asynchronous functions, available under Excel 2010 and later, are now supported. Runtime registration of delegate functions and external retrieval of registration details will allow development of extension features without requiring changes to the Excel-DNA core runtime.

Excel-DNA 0.32 is compatible with version 0.30, and introduces no notable breaking changes. See the Distribution\ChangeLog.txt file for a complete change list.

As always, I greatly appreciate any feedback on this version, and on Excel-DNA in general. Any comments or questions are welcome on the Google group or by contacting me directly.

To ensure future development of Excel-DNA, please make a donation via PayPal or arrange for a corporate support agreement. See http://excel-dna.net/support/ for details.

Thank you for your continued support,
Govert

Tutorial: COM server support for VBA integration

$
0
0

Functions and macros created in an Excel-DNA add-in can be called directly from Excel VBA by using Application.Run(…). However, .NET also supports creating rich object models that are exported as COM libraries, which can be Tools->Referenced in VBA. Excel-DNA has some advanced support to host COM-exported objects from Excel-DNA add-ins, giving some advantages over the regular .NET ‘Register for COM interop’ hosting approach:

  • COM objects that are created via the Excel-DNA COM server support will be active in the same AppDomain as the rest of the add-in, allowing direct shared access to static variables, internal caches etc.
  • COM registration for classes hosted by Excel-DNA does not require administrative access (even when registered via RegSvr32.exe).
  • Everything needed for the COM server can be packed in a single-file .xll add-in, including the type library used for IntelliSense support in VBA.

Mikael Katajamäki has written some detailed tutorial posts on his Excel in Finance blog that explore this Excel-DNA feature, with detailed explanation, step-by-step instructions, screen shots and further links. See:

Note that these techniques would works equally well with code written in VB.NET, allowing you to port VB/VBA libraries to VB.NET with Excel-DNA and then use these from VBA.

Thank you Mikael for the great write-up!

Excel-DNA 0.32 – Breaking changes to integer and boolean parameter handling

$
0
0

Excel-DNA version 0.32 introduces some changes in the parameter conversions applied to integer and boolean parameters. These changes improve compatibility with VBA, and make it easier to provide a consistent implementation when the conversion needs to be explicitly implemented, as for some generated methods.

In Excel-DNA versions before 0.32, UDF functions taking integer and boolean parameters were registered with the C API using the respective types, and hence the conversions were performed by Excel before calling the UDF. In Excel-DNA 0.32, these conversions are performed by Excel-DNA, with the changes discussed here. Affected functions would previously have behaved consistent with .xll add-ins made with C/C++, where registered with integer or boolean parameter types.

The new behaviour for integer conversions is that double values passed from Excel to integer parameters in UDFs are converted using the ‘Round-To-Even’ midpoint rounding convention. Previously, positive midpoint values (like 2.5) were rounded up (to 3), while negative midpoint values were rounded down (-2.5 to -3), with the exception that -0.5 was rounded to 0. Int64 (long) parameters are now also handled consistently.

One exception to the VBA compatibility guideline is that incoming boolean ‘true’ values passed to integer parameters are converted to 1, rather than -1 as would be the case with VBA. For this case I consider it more importatnt to be consistent with .NET conventions, whereby boolean ‘true’ values are represented by 1.

For conversions to boolean parameters, the main change is in how fractional values are converted to booleans. The new version is consistent with VBA – any non-zero value is converted to ‘true’.

I hope you will agree that the improved consistency is worth making these breaking changes, and that the decision will not cause any unexpected problems. As always, I appreciate any feedback, either directly or via the Excel-DNA Google group.

 


The following snapshot gives a good summary of the changes:

Image

The functions used are as follows:

public static object dnaConvertInt32(int value)
{
    return value;
}
Function VbaConvertInteger(value As Integer)
    VbaConvertInteger = value
End Function
public static object dnaConvertInt64(long value)
{
    return value;
}
public static object dnaConvertBoolean(bool value)
{
    return value;
}
Function VbaConvertBoolean(value As Boolean)
    VbaConvertBoolean = value
End Function

Excel-DNA 0.32 Released

$
0
0

I’ve posted a final release of Excel-DNA version 0.32 to CodePlex (https://exceldna.codeplex.com/releases/view/119190) and the NuGet package repository (https://www.nuget.org/packages/Excel-DNA).

Excel-DNA 0.32 consolidates a large number of bug fixes and improvements that have accumulated over the last year. In particular, a number of edge cases that affect Excel-DNA add-ins under Excel 2013 have been addressed.

Native asynchronous functions, available under Excel 2010 and later, are now supported. Runtime registration of delegate functions and external retrieval of registration details will allow development of extension features without requiring changes to the Excel-DNA core runtime – see the ExcelDna.CustomRegistration project for examples of the dynamic registration: https://github.com/Excel-DNA/CustomRegistration

Excel-DNA 0.32 introduces one breaking change: integer parameter conversions are modified to be consistent with VBA. Fractional values passed to functions with integer parameters are converted using the round-to-even convention – as is the case for VBA functions. This issue is discussed in more detail at http://excel-dna.net/2014/05/03/excel-dna-0-32-breaking-changes-to-integer-and-boolean-parameter-handling/

See the Distribution\ChangeLog.txt file for a complete list of changes in this version.

As always, I greatly appreciate any feedback on this version, and on Excel-DNA in general. Any comments or questions are welcome on the Google group or by contacting me directly.

To ensure future development of Excel-DNA, please make a donation via PayPal or arrange for a corporate support agreement. See http://excel-dna.net/support/ for details.

Excel-DNA 0.33 Release Candidate and License Change

$
0
0

Version 0.33 Release Candidate

Excel-DNA 0.33 contains a number of bug fixes and improvements, including a diagnostic logging approach based on the .NET Trace classes. More details can be found in the current ChangeLog.

This version will also be the foundation for a first release of the custom Registration extension and the ongoing work towards on-sheet IntelliSense for user-defined functions.

A release candidate for the new version is available

Please help me test that the new version works correctly in the many different ways, Excel and Windows versions, and languages where Excel-DNA add-ins run.

If you run into any unexpected behaviour bugs or regressions, please post to the Google group or contact me directly.

Also, if you are able to confirm that the new version works in a particular setting, please post that too. Details about what functionality you’ve tested and what operating environment (including .NET and Excel version) you are running with, would help me a lot.

License Change

For the Excel-DNA project, I’ve changed to the standard MIT license. This has become the most common open-source license aligned with my intention of making Excel-DNA free for all use, including commercial use.

If you have any concerns with this change, please let me know.

NuGet Packages

With this version, I am re-aligning the Excel-DNA package names on NuGet with the assembly names and standard naming conventions. The main packages for this release will be:

  • ExcelDna.AddIn – Includes the .xll and creates a complete add-in when installed into a Class Library project. This is update of the “Excel-DNA” package.
  • ExcelDna.Integration – Containts only the integration reference library, suitable for referencing in third-party libraries that are intended to be used in Excel-DNA add-ins. An update of the “Excel-DNA.Lib” package.

The old packages will be updated to refer to the new ones as dependencies, which should allow package updates to work correctly.

GitHub

The Excel-DNA project is (slowly) moving to GitHub.

  • The core library project can be found at https://github.com/Excel-DNA/ExcelDna, where the latest source versions are hosted.
  • The best documentation and links to related projects and other source is still found on the old CodePlex site.
  • For general questions and discussion about Excel-DNA, please continue use the Excel-DNA Google group.
  • Specific issues, bug reports and feature requests can be added to the GitHub Issues list.
  • For a permanent book-mark to the project, please use the Excel-DNA home page at http://excel-dna.net.

Thank you for your continued support of Excel-DNA!


Add-in spotlight: ACQ for interpolation

$
0
0

This is the first in an occasional series of posts about interesting Excel-DNA based add-ins.

Alex Chirokov’s ACQ add-in provides a library of interpolation routines for Excel. The add-in includes 1D and 2D interpolators, scatter plot smoothing and a Mersenne Twister random number generator.

To have a closer look:

Features I like about the add-in (apart from it using Excel-DNA) include:

  • A liberal open-source license
  • A clear and authoritative implementation of a particular domain
  • Very nice example of using object handles – an interpolator is build from the data, and then used to interpolate many values. ACQ has a clean implementation and great example of this technique.
  • All the functions have a common prefix (“=acq…”), making them easy to find in the function list, and use with the Excel-DNA IntelliSense extension.

Thank you for publishing a great add-in, Alex.

PS: ACQ has a bonus feature that implements a Sudoku solver (and generator)! See the write-up here: Sudoku Solver in Excel using C# and Excel-DNA

Excel UDF IntelliSense for Excel-DNA and VBA

$
0
0

I’m happy to announce the first official release of the IntelliSense extension!

Excel-DNA IntelliSense provides on-sheet help for UDF functions as they are entered into a cell formula, similar to the help available for built-in Excel functions.

intellisense1intellisense2

For Excel-DNA add-ins (v0.32 and later) that already provide descriptions in the [ExcelFunction] and [ExcelArgument] attributes, no extra work is needed.
Just download and open (or install) the latest ExcelDna.IntelliSense.xll add-in from the GitHub (https://github.com/Excel-DNA/IntelliSense/releases), and the IntelliSense will light up. (There is also a NuGet package for embedding the service into your add-in, making distribution a bit easier.)
 
For VBA functions, you can add an extra sheet with the IntelliSense descriptions, or add an external .xml file with the information, or embed as a the CustomXML part in the Workbook or .xlam add-in.
Then open (or install) the ExcelDna.IntelliSense.xll add-in to provide the display service. Charles Williams, of FastExcel fame, has a detailed write-up on adding IntelliSense for your VBA function – see https://fastexcel.wordpress.com/2016/10/07/writing-efficient-vba-udfs-part-15-adding-intellisense-to-your-udfs/.
 
For PyXLL users, the latest PyXLL 3.1 release offer built-in support for IntelliSense with the ExcelDna.IntelliSense.xll add-in installed. See https://enthought.pyxll.com/whatsnew.html#intellisense.
 
Other native .xll add-ins can also provide IntelliSense through an external .xml file.
 
Details and downloads are on GitHub:
* Detailed Usage Instructions: https://github.com/Excel-DNA/IntelliSense/wiki/Usage-Instructions including details for incorporating the library into your own add-in for easier distribution.
 
Public support and bug reports:
The Excel-DNA Google group (https://groups.google.com/forum/#!forum/exceldna) is the best place for general questions, comments etc.
Detailed bug reports and feature requests can be added to the GitHub issues list: https://github.com/Excel-DNA/IntelliSense/issues
 
Corporate support and private donations:
If you find Excel-DNA and extensions like the IntelliSense service useful, please support the project by arranging a corporate support agreement, or making a donation via PayPal. See https://excel-dna.net/support/ for details and contact information.

Excel-DNA version 0.34

$
0
0

Excel-DNA version 0.34 has been release and is now available

Please post any issues you run into to the Google group (https://groups.google.com/forum/#!forum/exceldna)
The easiest way to test the new version is by installing (or upgrading to) the ‘ExcelDna.AddIn‘ NuGet package.

Excel-DNA version 0.34 introduces a much improved build procedure for add-ins created using the NuGet package (thanks to a fantastic effort by @caioproiete !)

This replaces the error-prone post-build steps we had with a custom build helper and allows easier build output customization (see https://github.com/Excel-DNA/ExcelDna/wiki/Build-Output-Customization).
Various bug fixes and smaller improvements are also included in this version:
  • Add ExplicitExports=”false” to NuGet .dna file template
  • Fix getting Application from ProtectedViewWindow
  • Add attempts to get Application object from all windows of class EXCEL7.
  • Fix ExcelAsyncUtil.Observe re-open restart – broken by other fixes in the previous version. Add option to not restart.
  • Change ExcelRtdServer.ConnectData to be more careful about raising an update notice. Calls to Topic.UpdateNotify during the ConnectData overload are now always ignored. If the topic value is updated (through Topic.UpdateValue) during ConnectData, and the same value is returned from ConnectData, then no spurious UpdateNotify is raised. If the value returned from ConnectData differs from Topic.Value, UpdateNotify will still be raised.
  • Allow AccessViolation exceptions to be caught under .NET 4.0 – change marshaling wrapper from DynamicMethod to MethodBuilder.
  • Fix QueueAsMacro failure after paste live preview.
  • Fix AssemblyResolve re-entrancy race condition.

To make a donation to the project, or to arrange for a corporate support agreement that lets you ensure Excel-DNA will live on, please visit the Excel-DNA Support page.

Thank you for your continued support and enthusiasm towards the Excel-DNA project!

Develop Excel Conference – London, 18 October 2018

$
0
0

Charles Williams of FastExcel fame is hosting a one-day conference in
London on 18 October, covering a wide range of Excel extensibility topics.

I will be presenting Excel-DNA, joining developers responsible for PyXLL,
Planatech XLL+, the new Javascript interfaces from Microsoft, and more.
Anyone interested in advanced Excel extensibility will get great insights
into the present and future of developing Excel-based solutions.
Please join us!

This is a community organized pay-if-you-can event, with contributions helping to defer speakers’ travel expenses.

Find all the details and registration info at:
https://developexcel.wordpress.com

 

Excel-DNA version 1.0

$
0
0

A release candidate for Excel-DNA version 1.0 is now available on NuGet and as a direct download from GitHub. The easiest way to test is to install the pre-release NuGet package (package version 1.0.0-RC1):

Install-Package -Pre ExcelDna.AddIn
I hope to make a final release of version 1.0 in early April, soon after the release of Visual Studio 2019.
The Excel-DNA 1.0.x series (this version with minor fixes) will be final version to support older .NET (< 4.0) and Excel (< 2007) releases.
Version 1.0 is essentially the same as the long-overdue version 0.35. The update includes a number of bug fixes as well as improvements to the build-time Visual Studio integration:
  • Improve build tasks – more reliable clean-up and debugger detection
  • Improve RTD and async QueueAsMacro reliability
  • Improve install process of ExcelDna.AddIn NuGet package (now requires NuGet 2.5) (thanks to @caioproiete)
  • Change how ExcelDnaUtil.Application works in Protected View – try harder but don’t cache
  • Call UnhandledExceptionHandler for macros (ExcelCommands) too
  • Add XML schema for .dna file (thanks to @caioproiete)
  • Add option to pack .pdb files (thanks to @lanfeust69)
  • Fix exception handling from native async functions (thanks to @ittegrat)
Please post any issues you run into to the Google group (https://groups.google.com/forum/#!forum/exceldna)

To make a donation to the project, or to arrange for a corporate support agreement that lets you influence the future of Excel-DNA, please visit the Excel-DNA Support page.

Thank you for your continued support and enthusiasm towards the Excel-DNA project!

 

Viewing all 24 articles
Browse latest View live