VBA操作WORD(⼆):替换字符(含空格、全⾓字符、换⾏符
等)
这篇实现WPS⽂字⼯具提供的⼏个⼩功能:
Sub段落⾸⾏缩进转为空格()
Dim ib As Paragraph
For Each ib In ActiveDocument.Paragraphs
'排除表格
If ib.Range.Information(wdWithInTable) = False Then
ib.Range.Select
'缩进不⼀定是2个字符,只要缩进不为0就替换,避免标题、主送对象等误操作
If ib.Range.ParagraphFormat.FirstLineIndent > 0Or ib.Range.ParagraphFormat.CharacterUnitFirstLineIndent > 0Then
With Selection.ParagraphFormat
.CharacterUnitFirstLineIndent = 0
.FirstLineIndent = 0
End With
ib.Range.Words(1).InsertBefore "  "'插⼊2个全⾓字符
End If
End If
Next
End Sub
'第⼀个参数是⽬标替换字符串,第⼆个参数是替换后的字符串
Sub⾃定义替换(tarText As String, repText As String)
'Application.ScreenUpdating = False
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = tarText
replaceall()
.Replacement.Text = repText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.
MatchByte = True
.MatchWildcards = True'要设置为True,否则通配符不⽣效
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
ActiveWindow.ActivePane.VerticalPercentScrolled = 0
End Sub
Sub删除段⾸空格()
'含全⾓和半⾓空格;WPS只删空格
Call⾃定义替换("^13[  ]{1,}", "^13")
End Sub
Sub换⾏符转为回车()
Call⾃定义替换("^l", "^13") '换⾏符转为回车
End Sub
^p在微软Word中会报错,WPS中^13和^p都可以执⾏上⾯的代码。
'.Text = """(*)"""
'.Replacement.Text = ChrW(8220) & "\1" & ChrW(8221)
'也可以将空格、全⾓空格替换掉
'注意:如果表格中有回车符,会造成误操作。
Call ⾃定义替换("^13{2,}", "^p") '删除2或以上空⾏,^13是回车符,^p为段落标记
替换全⾓字符:
Dim qjsz, bjsz As String, iii As Integer
qjsz = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,/<>?;’:[]{}\|=-+_)(*%$#@!`~&" bjsz = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,/《》?;':【】{}\|=-+_)(×%$#@!'〜&"
Selection.WholeStory
For iii = 1To95
With Selection.Find
.Text = Mid(qjsz, iii, 1)
.Replacement.Text = Mid(bjsz, iii, 1)
.Format = False
.MatchWildcards = False
.
Execute Replace:=wdReplaceAll
End With
Next iii
全⽂搜索关键字(Exit Do没注释掉就表⽰匹配第⼀个):
Sub全⽂搜索关键字()
'注意下⾯三处Selection不是同⼀个对象。
Selection.HomeKey unit:=wdStory
Do While Selection.Find.Execute(FindText:="关键字", Forward:=True) = True        Selection.MoveStart unit:=wdParagraph, Count:=-1'选中关键字所在段落With Selection
'这⾥可以⽤Selection进⾏处理。
End With
Exit Do'第⼀次匹配成功就跳出循环,后⾯不处理
Loop
End Sub
--更新于2020/4/24--
1.增加段落⾸⾏缩进转为空格功能;
2.完善段落标记在微软word兼容问题。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。