如何修改Word VBA代码,复制文档内容时排除命令按钮?
解决Word VBA复制内容时排除命令按钮的问题
当前代码使用Selection.WholeStory会选中整个文档(包括ActiveX命令按钮),导致复制内容包含按钮。可以通过以下两种方式替换该部分代码,实现仅复制文档正文内容:
方法一:利用临时文档过滤控件(推荐)
这种方法更可靠,能确保所有类型的命令按钮都被排除:
Private Sub CommandButton2_Click() Dim cc As ContentControl Dim ff As Field Dim tempDoc As Document If ActiveDocument.ProtectionType <> wdNoProtection Then ActiveDocument.Unprotect End If ' 创建临时文档 Set tempDoc = Documents.Add ' 复制当前文档内容到临时文档 ActiveDocument.Content.Copy tempDoc.Content.Paste ' 删除临时文档中的所有ActiveX命令按钮 Dim inlineShp As InlineShape For Each inlineShp In tempDoc.InlineShapes If inlineShp.Type = wdInlineShapeOLEControlObject Then inlineShp.Delete End If Next Dim shapeObj As Shape For Each shapeObj In tempDoc.Shapes If shapeObj.Type = msoOLEControlObject Then shapeObj.Delete End If Next ' 复制过滤后的内容 tempDoc.Content.Copy ' 关闭临时文档,不保存 tempDoc.Close SaveChanges:=wdDoNotSaveChanges End Sub
方法二:直接调整选中范围(适用于控件较少的场景)
如果命令按钮都位于文档末尾,可以直接选中到最后一个控件之前的内容:
Private Sub CommandButton2_Click() Dim cc As ContentControl Dim ff As Field Dim lastCtrlRange As Range If ActiveDocument.ProtectionType <> wdNoProtection Then ActiveDocument.Unprotect End If ' 获取最后一个ActiveX控件的起始位置 Set lastCtrlRange = ActiveDocument.Content Dim inlineShp As InlineShape For Each inlineShp In ActiveDocument.InlineShapes If inlineShp.Type = wdInlineShapeOLEControlObject Then If inlineShp.Range.Start < lastCtrlRange.End Then Set lastCtrlRange = inlineShp.Range End If End If Next ' 选中从文档开头到最后一个控件之前的内容 ActiveDocument.Range(Start:=0, End:=lastCtrlRange.Start).Copy End Sub
说明
- 方法一通过临时文档中转,先复制所有内容再删除控件,能适配各种控件位置和数量的场景;
- 方法二更轻量化,但仅当所有命令按钮都集中在文档末尾时效果最佳。
内容的提问来源于stack exchange,提问作者Diane Rhoads
相关产品推荐
相关产品推荐

