因为个人习惯将所学归纳总结,常常写WORD,但是写完的代码只能以高清截图的方式放到WORD里面,查看的时候还得放大,同时图片多了之后整个WORD文档很臃肿,所以在网上搜索前人的经验之后,在此基础上增加了些许改动,使得代码可以放在WORD中直接查阅、复制、且更美观,且该方法适用于除了代码以外的很多事情,聪明的你一定能举一反三。
先看前后对比图,下图左图是以前我的WORD风格,右图是使用VBA宏后实现的风格:
后者相对来说一目了然,十分方便,以下介绍在WORD中插入代码的步骤:
1. 打开WORD,ALT+F11进入VBA设置,在NORMAL中插入一个模块,然后复制以下的代码到模块中,保存;
Sub SetTableFmt()
' author: code4101
' macro for set table format
'
'
' "morning" coloring scheme for background, RGB(229,229,229)
With Selection.Tables(1)
With .Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorAutomatic
.BackgroundPatternColor = 15066597
End With
.Borders(wdBorderLeft).LineStyle = wdLineStyleNone
.Borders(wdBorderRight).LineStyle = wdLineStyleNone
.Borders(wdBorderTop).LineStyle = wdLineStyleNone
.Borders(wdBorderBottom).LineStyle = wdLineStyleNone
.Borders(wdBorderVertical).LineStyle = wdLineStyleNone
.Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
.Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
.Borders.Shadow = False
.AutoFitBehavior (wdAutoFitContent) 'auto fit size
End With
With Options
.DefaultBorderLineStyle = wdLineStyleSingle
.DefaultBorderLineWidth = wdLineWidth050pt
.DefaultBorderColor = wdColorAutomatic
End With
' no indentation at firt line, line spacing: fixed value of 12 pounds
With Selection.ParagraphFormat
.LeftIndent = CentimetersToPoints(0)
.RightIndent = CentimetersToPoints(0)
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpaceExactly
.LineSpacing = 12
.KeepWithNext = False
.KeepTogether = False
.PageBreakBefore = False
.NoLineNumber = False
.Hyphenation = True
.FirstLineIndent = CentimetersToPoints(0)
.OutlineLevel = wdOutlineLevelBodyText
.CharacterUnitLeftIndent = 0
.CharacterUnitRightIndent = 0
.CharacterUnitFirstLineIndent = 0
.LineUnitBefore = 0
.LineUnitAfter = 0
.MirrorIndents = False
.TextboxTightWrap = wdTightNone
.AutoAdjustRightIndent = True
.DisableLineHeightGrid = False
.FarEastLineBreakControl = True
.WordWrap = True
.HangingPunctuation = True
.HalfWidthPunctuationOnTopOfLine = False
.AddSpaceBetweenFarEastAndAlpha = True
.AddSpaceBetweenFarEastAndDigit = True
.BaseLineAlignment = wdBaselineAlignAuto
End With
' 清除原有的段落底纹
Selection.ParagraphFormat.Shading.BackgroundPatternColor = wdColorAutomatic
' set font
With Selection.Font
.Size = 9.5
.Name = Consolas
End With
End Sub
Sub InputLinearNum()
' author: code4101
Line = InputBox("请输入代码终止行数", "输入行数", "50")
For i = 1 To Line - 1
Selection.TypeText Text:=i
Selection.TypeParagraph
Next
Selection.TypeText Text:=Line
End Sub
Sub SplitCell()
' author: code4101
Line = InputBox("请输入代码终止行数", "输入行数", "50")
Selection.Cells.Split NumRows:=Line, NumColumns:=1, MergeBeforeSplit:=True
End Sub
2. 打开VS或者DEVC++等其他编译工具,选择并复制要保存的代码;
3. 在WORD中插入一个1行2列的表格,将要保存的代码粘贴到第2列,然后选择整个表格,ALT+F8调用设置好的宏“SetTableFmt”,即可完成表格属性编辑;
4. 选择第1列,ALT+F8调用设置好的宏“InputLinearNum”,即可添加行号;
VBA代码中,还有一段代码用来实现单元格拆分,已经用不到了~