我有一个包含9个复选框的用户表单,每个复选框都与文档中的大纲级别1标题(样式Heading11)相对应。
我希望能够勾选任意数量的这些复选框,并从文档中删除选定的标题&该‘Heading11’/中的文本,直到下一个节。
例如,如果我勾选CbxISR和CbxPPL,将在文档中搜索Heading11文本“工业特殊风险”和“公共责任”。
我试图调整在使用.Find
方法的THIS线程中找到的代码,但它特定于只搜索一个不变的文本值。
如何使用已勾选的复选框?
发布于 2020-05-05 16:16:04
您可以遍历复选框,将每个标题的部分或全部文本和标题级别#传递给宏,如下所示,每个选中的复选框:
Sub DeleteHeadingSpanText(StrTxt As String, h As Long)
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = StrTxt
.Style = "Heading " & h
.Replacement.Text = ""
.Format = True
.Forward = True
.Wrap = wdFindContinue
.Execute
End With
If .Find.Found = True Then
.Duplicate.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel").Delete
End If
End With
End Sub
例如,假设您有一个标题1,其文本由以下内容组成:
Lorem ipsum dolor坐好了。
您可以通过以下方式删除与该标题关联的所有内容:
Sub Demo()
Call DeleteHeadingSpanText("ipsum dolor", 1)
End Sub
请注意,只需要标题中的部分字符串。还请注意,Word的标题样式只跨越‘heading1’到‘heading9’;没有'Heading11‘。
发布于 2020-05-15 10:15:28
我最终使用了下面的代码,它工作得很好。我想我会分享它,以防其他人为此而挣扎!
请注意,我在我的userform_Initialise sub中执行了CollapseAllHeadings操作,以确保它能正常工作。
Public Sub ComOK_Click()
'Warning msgbox confirm sections being deleted
Dim answer As Integer
Dim strResult As String
Dim strDelete As String
Dim obj As Object
strResult = "You are about to remove the following templates from this document:" & vbCr
For Each obj In Me.Controls
Select Case TypeName(obj)
Case "CheckBox"
If obj.Value = True Then
strResult = strResult & vbCr & obj.Caption
End If
End Select
Next obj
answer = MsgBox(strResult & vbCr & vbCr & "THIS CANNOT BE UNDONE after saving your document."
& vbCr & "Do you want to continue?", vbOKCancel, "WARNING")
If answer = vbOK Then
UserFormSections.Hide
Application.ScreenUpdating = False
'Delete sections from document
For Each obj In Me.Controls
Select Case TypeName(obj)
Case "CheckBox"
If obj.Value = True Then
strDelete = obj.Caption
Call DeleteHeading(strDelete)
End If
End Select
Next obj
Else
End If
'Expand remaining headings
With ActiveDocument.ActiveWindow.View
.ExpandAllHeadings
End With
'land back on titlepage after sub
ActiveDocument.Bookmarks("DeleteTemplate").Select
Application.ScreenUpdating = True
'Confirm delete to user
MsgBox "Your selected section(s) have been deleted.", vbOKOnly, "Deleted"
End Sub
Sub DeleteHeading(strText As String)
Dim HeadingF As Range
Set HeadingF = ActiveDocument.Content
'Search for match
With HeadingF.Find
.Style = "Heading 2"
.Text = strText
.Forward = True
.Wrap = wdFindStop
.MatchWholeWord = True
.MatchCase = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchAllWordForms = False
.Execute
End With
'Delete match
If HeadingF.Find.Found Then
HeadingF.Select
Selection.MoveEnd wdParagraph
Selection.Delete
End If
End Sub```
https://stackoverflow.com/questions/61607253
复制相似问题