konggs版主你好,我学习了你的代码,编写了一段程序,用于替换一个文档里面的空格(中文之间,中文与英文之间),但是英文与英文之间的正常空格需要保留。在一些文档里面这个代码能成功,但是附件这个文档,运行程序失败 1. Set objEditor =Selection.Editors(1) 但是这一句总是报错 请问是什么原因呢,这句代码的含义是什么,非常感谢 - Sub sckg() '将全文空格删除,但是保留英文之间的正常空格'
- Application.ScreenUpdating = False
- Dim characters1, characters2, n As Long, t
- characters1 = ActiveDocument.Characters.Count
- t = Timer()
- Dim reg As Object
- Set reg = CreateObject("VBScript.RegExp") '创建正则对象
- Dim i, j, mt, oRang As Range, m%
- '首先将文档的不间断空格,全部替换成普通空格,不间断空格的输入方法是Ctrl+Shift+Space,显示为一个个小圆圈
- Selection.Find.ClearFormatting
- Selection.Find.Replacement.ClearFormatting
- With Selection.Find
- .Text = "^s"
- .Replacement.Text = " "
- .Forward = True
- .Wrap = wdFindContinue
- .Format = False
- .MatchCase = False
- .MatchWholeWord = False
- .MatchByte = True
- .MatchWildcards = False
- .MatchSoundsLike = False
- .MatchAllWordForms = False
- End With
- Selection.Find.Execute Replace:=wdReplaceAll
- '替换完成
- With reg
- .Pattern = "[^a-zA-Z]\s+|\s+[^a-zA-Z]" '这里各显其能输入正则表达式
- .Global = True: .IgnoreCase = False: .MultiLine = True
- For Each i In ActiveDocument.Paragraphs
- For j = .Execute(i.Range.Text).Count - 1 To 0 Step -1 '从一段最后一个匹配的对象往前查找,这样可以避免删除空格之后firstindex变化导致替换发生错误
- Set mt = .Execute(i.Range.Text)(j)
- m = mt.FirstIndex: n = mt.Length
- Set oRang = ActiveDocument.Range(i.Range.Start + m, i.Range.Start + m + n)
- Dim objEditor As Editor
- '表示已被分配特定权限可编辑部分文档的单个用户。
- '可授予权限的用户包括单独的捐赠者以及为"文档工作区"站点定义的用户组。
- '得到三个Editor 对象
- Set objEditor = oRang.Editors.Add(wdEditorEveryone)
- Next
- Next
- ActiveDocument.Protect Password:="", NoReset:=False, Type:= _
- wdAllowOnlyReading, UseIRM:=False, EnforceStyleLock:=False
- ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
- ActiveDocument.Unprotect
- '去掉选中的Editor对象
- Set objEditor = Selection.Editors(1)
- objEditor.DeleteAll
- '任务窗格不显示
- CommandBars("Task Pane").Visible = False
- Application.ScreenUpdating = True
- End With
- With Selection.Find
- .ClearFormatting '取消查找的格式设置
- .Text = " " '查找内容
- .Replacement.ClearFormatting '取消需替换的格式设置
- .Replacement.Text = "" '替换的内容
- .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=False '执行全部替换,向前,到末尾继续从头查找
- End With
- Selection.ShrinkDiscontiguousSelection
- characters2 = ActiveDocument.Characters.Count
- n = characters1 - characters2
- MsgBox "共删除无用空格" & n & "个!" & vbNewLine & "用时:" & Format(Timer() - t, "0.000秒")
- Application.ScreenUpdating = True
- End Sub
复制代码
|