Commenting out code in multiple source files using Visual Studio

[Migrated content. Thread originally posted on 18 January 2011]

I was recently asked if it was possible to comment out multiple lines of code quickly?

Sure -- just select the code and choose comment/uncomment from Edit->Advanced menu.

What if these lines aren’t adjacent in the source code?

Here’s a VB macro you can import using the VS Macros IDE or Macros Explorer which might help.

It works from the output of the Find in Files results window. So you can search for the code you need to comment out and then run this macro to do the job.


Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module CommentOutFinds

    ' Run through all the hits in the find results window
    ' open each hit and comment it out.
    Sub TemporaryMacro()
        ' This gets the Find in Files Results Window
        Dim findResultsWindow As EnvDTE.Window = _
        DTE.Windows.Item(Constants.vsWindowKindFindResults1)

        ' I expect there's a more elegant way to do this...

        ' Get all the text in the window by selecting it
        Dim txtSel As TextSelection = findResultsWindow.Selection()
        txtSel.SelectAll()

        ' Determine number of lines in the string subtract the find pre- and post-amble
        Dim c As Int32 = txtSel.Text.Split(Environment.NewLine).Length - 3

        If c
            Return
        End If

        ' Do the commenting out
        Do Until c = 0
            DTE.Windows.Item(Constants.vsWindowKindFindResults1).Activate()
            DTE.ExecuteCommand("Edit.GoToFindResults1NextLocation")
            DTE.ExecuteCommand("Edit.CommentSelection")

            c = c - 1
        Loop

    End Sub
End Module