程序代码加行号及修改注释颜色为蓝色
在侯捷《word排版艺术》一书中有一个很实用的vba宏,可通过录制宏,打开vba代码窗口,然后添加如下代码:
Dim nLineNum '行号(数值)
Dim sLineNum As String '行号(文字)
Dim selRge As Range '用以记录整区块程序代码(多行)
Dim i '计数器
'以下变量用于“将注释改为蓝色”
Dim lineProgramRange As Range '单行程序代码范围
Dim commentRange As Range '注释范围
Dim TextLine As String '每一行程序代码(内容)
Dim ProgComment As String '每一行程序代码内的注释文字
Dim RgnStart As Long 'Start of a Range
Dim RgnEnd As Long 'End of a Range
Set selRge = Selection.Range '首先记录Selection
For nLineNum = 1 To selRge.Paragraphs.Count '针对每个段落
sLineNum = str(nLineNum) '行号转换为文字
sLineNum = LTrim(sLineNum) '去除开头和结尾的空格
For i = 1 To (3 - Len(sLineNum)) '补足三位数(前加0)
sLineNum = "0" + sLineNum
Next i
sLineNum = "#" & sLineNum '前加符号#
sLineNum = sLineNum + " " '前加空格
selRge.Paragraphs(nLineNum).Range.InsertBefore (sLineNum) '将行号插入到代码前
'将注释改为蓝色
Set lineProgramRange = selRge.Paragraphs(nLineNum).Range
TextLine = lineProgramRange.Text '取得整行文字(代码)
CharPos = InStr(1, TextLine, Chr(39)) '寻找注释起始点
If CharPos <> 0 Then
ProgComment = Mid(TextLine, CharPos + 1) '切割出注释文字
RgnStart = lineProgramRange.Start
RgnEnd = lineProgramRange.End
lineProgramRange.SetRange Start:=RgnStart + CharPos, End:=RgnEnd
lineProgramRange.Select
Selection.Font.ColorIndex = wdBlue '令注释为蓝色
End If
Next nLineNum
步骤如下: