如何删除整个Word文档中<de>
和单元格结束标记之间的文本?
我从上一个问题中获得了以下代码。看来行不通,因为我的行以单元格结束标记结尾。因此,现在我需要对其进行更新,以删除<de>
和单元格结束标记之间的文本。
我无法在此代码中实现。
Sub FindTheDeleteToEndOfLine()
Dim searchTerm As String
Dim bFound As Boolean
searchTerm = "<de>"
Selection.HomeKey wdStory
'Basic Find settings
With Selection.Find
.Forward = True
.wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
'Execute the Find
Do
With Selection.Find
.Text = searchTerm
bFound = .Execute
If bFound Then
Selection.MoveEnd wdLine, 1
Selection.MoveEnd wdCharacter, -1
Selection.Delete
End If
End With
Loop While bFound
End Sub
更新:我制定了一个不太复杂的新代码,但是我仍然不愿意定义arng.words
以便删除<de>
之后的最后一部分:
Dim arng As Range
Dim i As Long, j As Long
With Selection.Tables(1)
For i = 1 To .Rows.Count
For j = 1 To .Columns.Count
Set arng = .Cell(i, j).Range
arng.End = arng.End - 1
'Text = "<de>"
If Right(arng.Words, 1) = "<de>" Then
arng.Words.Last = Left(arng.Words, Len(arng.Words) - 1)
End If
Next j
Next i
End With
答案 0 :(得分:0)
您在这里遇到的问题是由于Word对单元格中的选择有何反应:一旦到达单元格的末尾,它就会选择整个单元格。
我已经修改了代码(使其更加“复杂”)以考虑到这一点。为了解决这个问题,代码中现在有一个Range
对象,用于存储文档中的原始“ Found”点。将选择范围扩展到该行的末尾,并将其移回一个字符(这意味着整个单元格都被选中)之后,将起点重新设置为“找到”位置。
Sub FindTheDeleteToEndOfCell()
Dim searchTerm As String
Dim bFound As Boolean
Dim rngFound As Word.Range
searchTerm = "<de>"
Selection.HomeKey wdStory
'Basic Find settings
With Selection.Find
.Forward = True
.wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
'Execute the Find
Do
With Selection.Find
.Text = searchTerm
bFound = .Execute
If bFound Then
Set rngFound = Selection.Range
Selection.MoveEnd wdLine, 1
Selection.MoveEnd wdCharacter, -1
Selection.Start = rngFound.Start
Selection.Delete
End If
End With
Loop While bFound
End Sub
答案 1 :(得分:0)
尝试,例如:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "<de>"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found
If .Information(wdWithInTable) = True Then
.End = .Cells(1).Range.End - 1
.Delete
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub