I’ve written lots of Excel macros in the past using the following development process:
- Record a macro.
- Open the VBA editor.
- Edit the macro.
I’m now experimenting with a Visual Studio 2008 “Excel 2007 Add-In” project (C#), and I’m wondering if I will have to give up this development process.
I know I can still record macros using Excel, but is there any way to access the resulting code in Visual Studio? Or do I just have to copy and paste then C#-ize it?
What happens with my “Personal Macro Workbook”? Can I use the macros I have stored in there within C#? Or is there some way to convert them to C#?
If there is some support for opening and editing VBA macros in Visual Studio, can you provide a very brief summary of how it works or point me to a good reference?
Do you have any other tips for transitioning from writing macros in VBA using Excel’s built-in editor to writing them in C# with Visual Studio?
You are in for a world of hurt, if you want to port VBA macros to C#. If they are complex at all, I would just rewrite them in Visual Studio or keep them in Excel.
Also, as much as it pains me to say this, VB.net is really a better choice to do office development in at the moment. VB.net supports missing parameters which will come in handy for the Excel methods with a zillion parameters. This support will be added to C# for .NET 4.0.
You should be able to call a VBA method from .NET. Take a look at this:
You can also look at this article on codeproject: http://www.codeproject.com/KB/office/extending_excel.aspx
(Disclaimer: I develop the Excel-DNA library.)
You should have a look at Excel-DNA – http://exceldna.codeplex.com. The library allows managed assemblies written in C#, VB.NET or F# to expose high-performance user-defined functions (UDFs) and macros to Excel through Excel’s native .xll interface. The project is open-source and freely allows commercial use.
With your VBA background, it might make sense to move to .NET using VB.NET first. Once you’ve made this shift, starting to use C# will be much easier and you can cross-reference assemblies written in VB.NET and C# with no problems.
Some add-in tools like ReSharper, and the free .NET IDE SharpDevelop, can even convert code from VB.NET to C# automatically. Certainly for using the COM automation interface from C# you want to use .NET 4.
Mike Staunton has a video of a talk discussion the VBA -> VB.NET via Excel-DNA technique here: http://www.thalesians.com/finance/index.php/Events/Seminars/Seminar27#Video.