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 = _

        ' 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()

        ' 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
        End If

        ' Do the commenting out
        Do Until c = 0

            c = c - 1

    End Sub
End Module