How To Create and Run a Macro in Visual Studio .NET
- 06 Dec 2005 16:42
Welcome to my new blog. Here I will share some of my tips and tricks about VS that I learned or other people have asked for.
I start with the basic lesson about macros. Macros are still undiscovered area for many VS users though creating a macro is a quite simple task. Some people don't have time to play with macros, some don't know what they can use macros for and some even don't know that there are any macros in Visual Studio. This post is for all those people.
I will present several macros in the future so it is good idea to show how to put them in your Visual Studio and how to run them. Macro is nothing more than a function written in VB .NET and placed under your Macros. I can hear you asking: "Can I write macros using C# or some other language?". No, you cannot. Even when you are programming in C# or C++, your macros must be written in VB .NET. But don't worry, you don't need to learn VB .NET to try my macros. You will either record your macro in VS or copy and paste the code from here.
A macro can be created in two ways:
- Recorded in VS. This is mostly used when you want to create macro to automate repetitive tasks. These tasks mostly consists of steps that can be performed by using VS menus and dialogs. A macro only remembers all your actions. I will not talk about this kind of macros in the future. You can read more in "Recording Macros"
- Manually written. As previously mentioned, you can write your macro in VB .NET. We must use this method when we want to extend the functionality of VS instead of just recording the sequence of the actions. Macros can be really powerful and you can get desired effect without the need of writing an add-in.
- Open Macro Explorer. Go to Tools - Macros - Macro Explorer
- Navigate to Macros - MyMacros. Here you can either use existing Module1 or create your own module by right-click and New Module...
- Double click your module (e.g. Module1) to open Macros IDE.
Write your macro inside Public Module Module1. Module1 is replaced by your module name if you are using different module. As I wrote, macro is VB .NET function. You can try the following simple macro which shows a message window:
Sub test() MsgBox("This is my macro") End Sub
- Close Macros IDE.
To run the macro:
- In Macro Explorer, double click test macro under your module (right-click and Run in VS 2005). This will run your macro which shows a message.
- There are several other ways to run macro. You can for example assign a shortcut to it or create a button in menu or toolbar. I will show the latter in the next post. For more info see "Running Macros".