Running Excel Macro

479 views
Skip to first unread message

Jack

unread,
Oct 16, 2009, 8:43:56 AM10/16/09
to ExcelDna
Is there a way to run an excel macro (assuming it has no return or
parameters) from .net using Excel.Integration? For example, suppose I
have a macro in a worksheet called "Macro1" and I have a function in
c# called static double DoMacro1AndStuff(), can I have something
similar to:

static double DoMacro1AndStuff()
{
//--- run Macro1
return 1;
}

Govert van Drimmelen

unread,
Oct 16, 2009, 9:49:27 AM10/16/09
to ExcelDna
Hi Jack,

You can use xlcRun or xlUDF to run another macro or a VBA macro from
your _macro_ (see below).

Try something like in a .dna file:

<DnaLibrary Language="C#">
<![CDATA[
using ExcelDna.Integration;

public class Test
{
[ExcelCommand(MenuName="Cool Stuff", MenuText="DoCoolStuff")]
public static void DoStuff()
{
Excel(XlCall.xlUDF, "TheCoolStuff");
// Or try Excel(XlCall.xlcRun, "TheCoolStuff");
}

public static void TheCoolStuff()
{
System.Console.Beep();
}

}
]]>
</DnaLibrary>

Notes:
1. Apparently there is a bug in Excel 2007 that stops xlcRun from
working with VBA functions - fixed in this hotfix:
http://support.microsoft.com/default.aspx/kb/956836.
2. You won't be able to do anything wild when running from a user-
defined function that is called from a worksheet. Excel places
restrictions on what can be done while in the calculation context, so
for example you won't be able to set the values of cells while
calculating a function.
3. A common way to deal with this is to set an xlcOnTime (search for
this term) timer in your function, which will call the macro after the
recalculation is done, in a context where more is allowed.

Hope this helps.

Govert

Jack

unread,
Oct 16, 2009, 1:48:51 PM10/16/09
to ExcelDna
This does help. I was looking for exactly something like xlUDF. Too
bad Excel won't let you run anything "wild" from a Macro started from
the formula line. I was hoping to get away from that. Oh well, back to
OnTime, which I was sort of hoping to avoid.
Reply all
Reply to author
Forward
0 new messages