Format all files in project

Yesterday I discovered an awesomely useful Visual Studio macro: it applies that code formatting rules to all files in the whole solutions. Code formatting includes indentation, spacing, tabs vs. spaces: all the things that people tend to get irate about. By default, these formatting rules are applied only when you write new code. To apply them to an existing page, there’s the command Edit --> Format Document with the keyboard chord Ctrl-K, Ctrl-D. Now this macro goes and opens all files and applies this command – a very good idea to do before a major commit.

Sub FormatProject() 
    For Each Proj As Project In DTE.Solution.Projects 
        For Each Item As ProjectItem In Proj.ProjectItems 
            Dim window As EnvDTE.Window 
                window = Item.Open() 
                DTE.ExecuteCommand("Edit.FormatDocument", "") 
            Catch ex As Exception 
            End Try 
End Sub

Found as a comment by saraford to this MSDN post from 2005.


Christian is a software architect/developer. He lives in Germany, reads a lot, and likes cycling.

Tagged with: ,
Posted in Coding, Tools

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: