Comment / Uncomment macros

These macros were contributed by Guy Gascoigne – Piggford


Here are a couple of macros that I find very useful, they allow you to
comment or uncomment out the current line or selection. CommentOut is
based upon a similar macro that was shipped with Visual Studio but trimmed
to suit my needs better, the UnCommentOut function will reverse it’s effects.


To use: take these two definitions and paste them into your current macro
file, and save. For ease of use I bind these to a pair of keys, in my case
I bind Ctrl+/ to CommentOut and Ctrl+. to UnCommentOut.


Sub CommentOut ()
‘DESCRIPTION: Comments out a selected block of text.
Dim win
set win = ActiveWindow
if win.type <> “Text” Then
MsgBox “This macro can only be run when a text editor window is active.”
else
CommentType = “//”

StartLine = ActiveDocument.Selection.TopLine
EndLine = ActiveDocument.Selection.BottomLine
If EndLine < StartLine Then Temp = StartLine StartLine = EndLine EndLine = Temp End If If EndLine = StartLine Then ActiveDocument.Selection = CommentType + ActiveDocument.Selection Else For i = StartLine To EndLine ActiveDocument.Selection.GoToLine i ActiveDocument.Selection.SelectLine ActiveDocument.Selection = CommentType + _ ActiveDocument.Selection Next End If End If End Sub Sub UnCommentOut () 'DESCRIPTION: Uncomments a selected block of text. Dim win set win = ActiveWindow if win.type <> “Text” Then
MsgBox “This macro can only be run when a text editor window is active.”
else
StartLine = ActiveDocument.Selection.TopLine
EndLine = ActiveDocument.Selection.BottomLine
If EndLine < StartLine Then Temp = StartLine StartLine = EndLine EndLine = Temp End If For i = StartLine To EndLine TmpBlock = "" ActiveDocument.Selection.GoToLine i ActiveDocument.Selection.SelectLine CmtBlock = ActiveDocument.Selection Trim(CmtBlock) If Instr(CmtBlock,"//”) <> 0 Then
TmpBlock = TmpBlock + Left (CmtBlock, Instr (CmtBlock,”//”) – 1)
CmtBlock = Right(CmtBlock, (Len(CmtBlock) – (Instr(CmtBlock, “//”) + 1)))
CmtBlock = TmpBlock + CmtBlock
End If

ActiveDocument.Selection = CmtBlock
Next

End If
End Sub


Here’s an update by Todd Crooks.


It uses regular expressions to add or remove comments.


Sub BlockComment()
ActiveDocument.Selection.ReplaceText “^”, “//”, dsMatchRegExp
End Sub

Sub BlockUncomment()
ActiveDocument.Selection.ReplaceText “^//”, “”, dsMatchRegExp
End Sub

Updated on: October 30, 1998

More by Author

Previous articleSubselection Dialog
Next articleGDexpi

Must Read