VB .Net Revit
VB .Net Revit
VB .Net Revit
IT11135‐L
Getting Started with Revit Macros
Michael Kilkelly AIA
Space Command / ArchSmarter.com
Learning Objectives
Discover the differences between Revit macros, add‐ins, and external applications.
Learn how to create custom macros in Revit using the Revit macro editor and the VB.Net
programming language.
Learn how to utilize resources from the Revit Software Development Kit to get more information
about .NET and the Revit API.
Learn how to create time‐saving macros using a step‐by‐step process to break complex problems
into manageable tasks.
Description
We've all been there—it's an hour until your deadline and your project manager wants to make a few
“simple” changes. The problem is, these changes will take hours of tedious work . . . hours you simply
don't have. However, through the power of the Revit Application Programming Interface (API) and some
basic knowledge of computer programming, you can write macros to automate Revit software and save
a ton of time on your next project. This lab is designed to get you started automating Revit software
using macros written in the Microsoft Visual Basic .NET programming language. Over the course of this
lab, we'll cover programming basics and dive into the Revit API. We'll do this by writing useful macros
you can take back to your office and put to good use. At the end of the class you'll have a solid
foundation from which to start writing your own macros. Take command of your software and learn to
program! This class is geared toward intermediate‐to‐advanced Revit software users with little or no
programming experience.
Your AU Expert
Michael Kilkelly is the founder and principal of Space Command, a design and technology firm in
Middletown, Connecticut. He has extensive experience working on diverse, large‐scale projects, including
sporting arenas, residential towers, and performance halls. Equally versed as a technologist, he has built
numerous database and web applications as well as custom software to support the design process.
Prior to founding his firm in 2012, Michael worked for a number of internationally recognized design
firms, including Gehry Partners, LLP; Martha Schwartz Partners; ADD Inc.; and The S/L/A/M
Collaborative. Michael received his BArch from Norwich University in 1995 and his MS in design and
computation from Massachusetts Institute of Technology in 1999. Michael is also the founder of
ArchSmarter.com, a website dedicated to helping architects work smarter—not harder.
Getting Started with Revit Macros
What are Macros?
Macros are one of the easiest ways to Automate Revit and access the inner workings of the software.
Macros do not require any additional software other than Revit and are a great way for beginners to
learn programming.
So what exactly is a macro? A macro is a user created command that is coded using Revit’s API or
Application Programming Interface. Macros are run directly inside of Revit and are saved in the project
file. Other applications, like Microsoft Excel and Word, also have the ability to create macros. Revit
macros are different from those in Excel and Word because you cannot record actions directly into a
macro. Revit macros must be coded by hand.
Getting Started with Revit Macros
To get started writing your own macros, you should first install the Revit 2016 Software Development Kit
or SDK. The SDK contains help files and sample code that will assist you as you learn to program macros.
The Revit 2016 SDK be installed from the main page of the Revit installer or it can be downloaded from
the Autodesk’s website using the following URL: http://autodesk.com/developrevit.
The SDK will install on your hard drive and create the following subfolders and files. Take some time to
review the files. The macro samples are particularly useful as you get started creating your own macros.
Figure 1: Revit SDK folder
Also, open up the “RevitAPI.chm” file. This help file documents the entire Revit API. It is extremely
useful, though not particularly user friendly. The help file acts as a roadmap to the API. It is not a step‐
by‐step guide to programming Revit.
2
Getting Started with Revit Macros
Write Your First Macro
Ready to write your first macro? As you’ll see, the process is very easy. Follow the steps below and you’ll
be on your way to macro mastery.
1. Open the Macro Manager
Create a new project file. Click the Manage ribbon then click the Macro Manager icon. This will open the
Macro Manager dialog.
Figure 2: Manage ribbon and Macro Manager icon
Macros can reside in a project file or within the Revit application. Macros saved in the project file can be
used by any user who opens that file. Macros saved in the application are saved to the user’s Revit
configuration. These macros can be used on any model file but only by the user who created the macro.
Figure 3: Macro Manager dialog
3
Getting Started with Revit Macros
2. Create a New Module
Macros are organized in modules. When creating a macro in a new project file, you must first create a
module. A module is simply a collection of macros. A single project file can contain several modules with
each module having its own macros. Module names cannot contain spaces or special characters
To create a module, click the “Project 1” tab then click the Module button in the “Create” section. In the
“Create a New Module” dialog box, title your module “MyFirstModule. You can write macros in C#,
VB.Net, Python or Ruby. For this exercise, choose VB.Net as the module’s language. Click OK to create
the module.
Figure 4: Create New Module dialog
Once Revit has created the module, SharpDevelop will launch. SharpDevelop is an open‐source
development environment that is built into Revit for programming macros.
4
Getting Started with Revit Macros
3. Create a New Macro
Now that you have a module, you can create a macro inside the module. Click the Macro button in the
“Create” section of the Macro Manager dialog. In the “Create a New Macro” dialog, title your first macro
“MyFirstMacro” and set the language to VB.Net. Click OK to create the macro.
Figure 5: Create New Macro dialog
4. Write the Macro
Switch over to SharpDevelop. You’ll see the standard VB.Net code that is automatically generated when
you create a new module. Toward the bottom you’ll see the starting code for “MyFirstMacro”.
Your first macro is simply going to popup a message box in Revit. It only takes one line of code. After
“Public Sub MyFirstMacro()”, type the following between the “Public Sub” and the “End Sub” lines:
TaskDialog.Show(“My First Macro”, “Hello World!”)
The complete code should look like this:
Public Sub MyFirstMacro()
TaskDialog.Show(“My First Macro”, “Hello World!”)
End Sub
Make sure you add the closing parenthesis at the end of the TaskDialog line. This closes the TaskDialog
command.
5
Getting Started with Revit Macros
5. Build the Macro
Once you’ve typed the code, you’re ready to compile or “build” the macro. All macros must be built
before Revit can run them. In the SharpDevelop menu bar, select “Build” then “Build Solution”.
Figure 6: Build Solution tool
SharpDevelop will compile your VB.Net code into the .Net intermediate code. Any errors or warning will
show up in the Errors and Warning window located at the bottom of the SharpDevelop interface.
Figure 7: SharpDevelop error window
If you have an error, double‐check your code. The code window will list errors by line number so they
are easy to pinpoint.
6
Getting Started with Revit Macros
6. Run the Macro
If your macro compiled correctly, go back to Revit and open the Macro Manager dialog (Manage >
Macro Manager). You should see “MyFirstMacro” in the list below “MyFirstModule”.
Figure 8: Macro Manager dialog
Select “MyFirstMacro” from the list then click the Run button. This will execute your macro. You should
see the following on your screen:
Figure 9: Hello World dialog
7
Getting Started with Revit Macros
You did it! You wrote your first Revit macro. To take this further, you can modify the code to report back
something more useful. Change your code to the following:
TaskDialog.Show("My First Macro", "The current model is" _
& Me.Application.ActiveUIDocument.Document.PathName)
The “Me.Application.ActiveUIDocument.” object represents the current model file. The “Document”
object contains data pertaining to the current file itself. “PathName” is a property that represents the
path to the current model. If you want to display the active view in the current project file, change
“Document.PathName” to “ActiveView.Name”.
A quick note – the underscore in the first line of code sample above represents a line break in the code.
It tells SharpDevelop that the code continues on the line below. It is used primarily to fit the code onto
the printed page. When you’re writing the code, you can ignore the underscore and type all of the code
on a single line.
Next Steps
Congratulations! You’re on your way to Revit macro mastery. The next challenge is learning to write
code and utilize the Revit API. While teaching all the details of programming is beyond the scope of this
workshop, I will highlight some key areas to guide you on your journey.
8
Getting Started with Revit Macros
Choose a Programming Language
In the example above, we used VB.Net to write the macro. VB.Net is just one of four languages you can
use to write macros. Since Revit uses the Microsoft .Net framework 4.0, you can write macros in either
Python, Ruby, C# or VB.Net. All these languages compile into the same intermediate language so you
have full access to Revit’s API from any of the languages.
Below is additional information about the supported language as well as pros and cons to each.
Language History Pros Cons
C# Based on C and C++ Lots of Revit specific The languages syntax is
code samples available not as readable as
online. You can use C# other languages. The
to develop stand‐alone code is more terse, is
desktop applications. case sensitive and uses
obscure symbols
VB.Net Evolved from VB.Net code is easier VB.Net is “wordier”
Microsoft’s Visual Basic to read than C#. The than C# ‐ it takes more
Language language is not as strict lines of code to do the
as C#. You can use same thing. Some say
VB.Net to develop the language isn’t as
desktop applications. elegant as other
languages.
Python Created in 1991 by Lots of general code Not many Revit specific
Guido van Rossum. samples and learning code samples available
resources available. online yet. Some
Easy to learn. Python debugging features not
code is very readable. available in
Can build web and SharpDevelop
desktop apps using
Python.
Ruby Created in 1995 by Lots of general code Not many Revit specific
Yukihiro Matsumoto. samples and learning code samples available
resources available. online yet.
Easy to learn. Code is
very readable. Can
build web apps with
Ruby.
VB.Net will be used for the code examples that follow.
9
Getting Started with Revit Macros
Converting Code from One Language to Another
SharpDevelop can convert code from one language to another. If you find a good Revit code sample
written in VB.Net, you can easily convert it to VB.Net.
To convert code, simply create a module and macro using the language of the code sample then, in
SharpDevelop, select Project > Convert and choose the language to convert the code into.
Fig. 10 – Converting code in SharpDevelop
Note that the conversion process is not always perfect. Sometimes you may find the code converts into
a string of gibberish, unfortunately.
Learning the Revit API
As you move beyond your first Revit macro, you’ll need to get familiar with the Revit API. The best way
to do that is through the Revit API help file. The help file is your roadmap to learning the API. You can
find the help file in the Revit 2016 SDK folder. Open the RevitAPI.chm file and click the “Content” tab.
The help file lists all of the namespaces in the Revit API.
A namespace is essentially a hierarchical container for the elements within the API. A good analogy for
namespaces is your computer’s folder structure. Each folder at the same level of the directory structure
must have a unique name. The folders can contain similarly named files but the path to each file will be
unique as the folder names are unique. Namespaces work the same way. There may be elements within
the API that are named the same. For example, many elements have a “Geometry” property but
namespaces provide a way to accurately identify which geometry you’re specifying. To reference the
wall geometry property, you type Autodesk.Revit.DB.Wall.Geometry.
10
Getting Started with Revit Macros
To find more information about a specific element within the API, simply drill down through the
namespaces to find the element. For instance, if I want to learn more about the properties of wall
objects, I click Autodesk.Revit.DB Namespace > Wall Class > Wall Properties. The help file lists all the
properties of wall elements.
Fig. 11: Revit 2016 API help file
Reading the API help file is not easy. It takes some practice as it is not written in plain English. Rather, it
is a description of all the elements within the API. The help file does contain code samples but it not a
learning tool. Much like a road map will not teach you to drive a car, the API help file will not teach you
to code but it will help you get where you’re going.
Troubleshooting Macros
You will spend a lot of time troubleshooting and debugging your macros. One of the great things about
coding is that the feedback is immediate. You write some code, compile it then run it. Your code will
either work or it will not. Revit will tell you immediately if it does not work and you will feel a sense of
accomplishment when it does work. SharpDevelop provides a number of tools to assist you while
troubleshooting your code.
Using Debug.Print and the Output Window
While writing code, it is often useful to have your macro report back information while the macro is
running. Writing code is an iterative process and you will need feedback as you develop your macro.
11
Getting Started with Revit Macros
SharpDevelop’s output window is useful for understanding what’s going on inside your macro.
To output information to the output window, use the “Debug.Print” command. Before you can use the
command, however, you’ll need to add the Systems.Diagnostics namespace to your macro. You do this
by typing “Imports System.Diagnostics” to the beginning of your macro code.
Figure 13: Macro import statements
Stepping Through Your Code
When you compile your code and run it, Revit will run through the code sequentially. While writing
macros however, it is often useful to step through your code line by line so you can see exactly what is
going on. You can step through your code using the Step Into button in the “Macro Manager” dialog.
Figure 13: Macro Manager dialog box
12
Getting Started with Revit Macros
Press the F10 key to step through each line of code. While you are walking through the code, you can
view the Output window to see any output from your “Debug.Print” code. You can also view the
current values in your variables through the “Local Variables” tab.
Using Break Points
In addition to stepping through your code, you can set specific points where you want the code to stop
running so you can check out the Output or Local Variables windows. Clicking on the grey area to the left
of the line number row will create a break point. A break point is represented as a red dot. Any line
containing a break point will also be highlighted in red. When Revit encounters a break point when
running the code, it will stop executing the code. Pressing F10 will step through your code or press F5 to
continue running the remainder of the macro.
Figure 14: Adding breakpoints
Commenting Your Code
One of the most critical practices to follow when writing code is to add comments as you are writing
your code. These comments should serve as a reminder for what the code does and why it’s structured
in that particular way.
Each language has its own syntax for writing comments. Comments are identified in VB.Net by an
apostrophe at the beginning of the line. SharpDevelop highlights all comments in green.
‘This is a VB.Net comment
Comments can also be used to block code from running. Say you are testing some alternate approaches
to a specific part of the macro. You can “comment out” parts of the code that you do not want to run. If
you have three options for the code, comment out two and run the macro with one of the options.
Commenting out can also be used to test very specific parts of your macro. If you are getting errors from
one section of the macro, comment out everything else, build the macro and step through it. This
focused approach will save you a lot of time while troubleshooting.
13
Getting Started with Revit Macros
Exceptions
Face it, your code is not going to be perfect. Even if your code compiles without an error, it can still
crash or throw an exception when you run it. This is simply the nature of coding. If you get an error, use
the methods listed above to systematically work through your code to identify the problem. This can
seem like finding a needle in a haystack when you are first starting out but as you code more and more
macros, you will get better at identifying problems in your code.
Figure 14: Macro error message
14
Getting Started with Revit Macros
Macro Sample
Our first macro was perfect for illustrating the process for creating a macro but let us take what we just
learned and put it to use on a macro that is more useful. The following code deletes unused views in the
current model file. If a view is not on a sheet, the macro deletes the view. Note this macro does not
work with dependent views.
Public Sub DeleteUnusedViews()
'set current document
Dim curDoc As Document = Me.Application.ActiveUIDocument.Document
'collect all views in current model file
Dim viewCollector As New FilteredElementCollector(curDoc)
viewCollector.OfCategory(BuiltInCategory.OST_Views)
'collect all sheets in current model file
Dim sheetCollector As New FilteredElementCollector(curDoc)
sheetCollector.OfCategory(BuiltInCategory.OST_Sheets)
'get sheet to test views against
Dim tempSheet As ViewSheet
tempSheet = sheetCollector.FirstElement
'create list of views to delete
Dim viewDeleteList As New List(Of View)
'create string for list of views
Dim viewDeleteString As String = ""
'loop through each view and check if it can be put onto a sheet
For Each curView As View In viewCollector
'check if current view is a template ‐ skip view if template
If curView.IsTemplate = False Then
'check if view can be put on sheet ‐ if it can then put in _
list of views to delete
If Viewport.CanAddViewToSheet(curDoc, tempSheet.Id, _
15
Getting Started with Revit Macros
curView.Id) = True Then
'add view to delete list
viewDeleteList.Add(curView)
End If
End If
Next curView
'if there are views to delete then delete them
If viewDeleteList.Count > 0 Then
'create transaction and delete unused views
Using curTrans As New Transaction(curDoc, "Delete views")
If curTrans.Start = TransactionStatus.Started Then
'loop through views to delete list and delete views
For Each deleteView As View In viewDeleteList
'add view to deleted view string
viewDeleteString = viewDeleteString & " " & _
deleteView.Name & ", "
'delete view
curDoc.Delete(deleteView.Id)
Next
End If
'commit changes to the model
curTrans.Commit
End Using
End If
'alert user
TaskDialog.Show("Deleted Views", "Deleted the following views: " & _
viewDeleteString)
End Sub
16
Getting Started with Revit Macros
Next Steps
What else can you do with Revit macros? Pretty much anything you can think of! Good candidates are
tasks that are fairly standardized or require lots of user input. Some examples include:
Update all window family instances with manufacturer data from spreadsheets.
Check that all doors in fire‐rated walls are actually fire‐rated doors.
Rename all custom families in the project file using a specific prefix for your company.
Automatically place specific views on a sheet.
Think about the tasks you do on a regular basis. Which of these do you like the least? Would you like to
automate it? Could you write a macro that would do the task for you?
Additional Resources
Want to learn more about writing your own macros? Check out these resources for more information.
• Online Courses
– Learn to Program the Revit API ‐ https://www.udemy.com/revitapi/
– Mastering Revit Macros – http://learn.archsmarter.com
• Blogs
– The Building Coder ‐ http://thebuildingcoder.typepad.com/
– ArchSmarter – http://archsmarter.com
– Boost Your Bim ‐ http://boostyourbim.wordpress.com/
– The Proving Ground ‐ http://wiki.theprovingground.org/revit‐api
• Online Forums
– Augi ‐ http://forums.augi.com/forumdisplay.php?218‐Revit‐API
• Books
– Autodesk Revit 2013 Customization with .Net How‐to by Don Rudder
Conclusion
Learning to write macros and automate Revit will drastically improve your efficiency. A well‐written
macro can do more in five minutes than a regular user can accomplish in one hour. Learning to program
takes time and patience. Start small and work systematically. You’ll be on your way to macro mastery in
no time!
17