在word中可以使用保护功能限制用户对word文档的内容进行编辑,同时可以选中例外项使得某些区域可以编辑。
在vba中可以使用Document对象的SelectAllEditableRanges方法选中所有可以编辑的区域,也可以使用DeleteAllEditableRanges方法删除所有可以编辑的区域。
还可以使用Range对象和Selection对象的GoToEditableRange方法遍历每个可以编辑的区域。
以下vba代码举例演示了如何遍历一个word文档的所有可编辑区域的方法:
Sub QQ1722187970()
Dim oDoc As Document
Dim oRng As Range
Set oDoc = Word.ActiveDocument
With oDoc
'一次性选中所有可以编辑的区域
.SelectAllEditableRanges
'先选中第一个可编辑区域
Set oRng = .Content.GoToEditableRange
oRng.Select
i1 = oRng.Start
'循环所有可以编辑的区域
Do
Set oRng = oRng.GoToEditableRange
oRng.Select
i2 = oRng.Start
Loop Until i1 = i2
End With
End Sub
如果要设置是否突出显示可编辑的区域,需要用View对象的ShadeEditableRanges属性设置,代码如下:
Sub QQ1722187970()
Dim oDoc As Document
Dim oRng As Range
Set oDoc = Word.ActiveDocument
With oDoc
If .ProtectionType = wdNoProtection Then
.Protect wdAllowOnlyReading, True, "123", False, False
Else
.Unprotect "123"
End If
'不突出显示可编辑的区域
.Windows(1).View.ShadeEditableRanges = False
End With
End Sub


发表评论