我想要创建一个宏,它允许选择文档中的整个代码块。
这就是我目前的情况:
Sub SelectSnippet()
Selection.Find.Style = ActiveDocument.Styles("Code")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
End Sub问题是,它只选择下一行代码,而不是完全选择代码片段。
视觉:

发布于 2017-09-19 11:37:10
这段代码应该可以完成这项工作。请试一试。
Sub SelectSnippet()
Dim Styl As Variant
Dim Rng As Range
Dim Fnd As Boolean
Styl = "Code"
Set Rng = Selection.Range ' start at the selection
' find the nearest different style before the selection
With Rng
Do While .Start > 1
If .Style <> Styl Then Exit Do
.Move wdCharacter, -1
Loop
End With
' look for the first occurrance of the style
On Error Resume Next
With Rng.Find
.Text = ""
.Style = Styl
Fnd = .Execute
End With
If Err Then
MsgBox Err.Description, vbInformation, "Can't find """ & Styl & """"
End If
If Fnd Then
' expand the range to the end of the style
With Rng
Do While .End < .Document.Characters.Count
If .Document.Range(.End, .End + 1).Style <> Styl Then Exit Do
.MoveEnd wdCharacter, 1
Loop
.Select ' select the range
End With
End If
End Sub下面的代码做同样的工作,但只查看完整的段落。如果一个段落的一部分不是相同的风格,它可能包括,也可能不包括在内。
Sub NewSelectSnippet()
Dim Styl As Variant
Dim Rng As Range
Dim DocRng As Range
Dim p As Integer
Styl = "Code"
' expand the section to include the entire paragraph
Set Rng = Selection.Paragraphs(1).Range
If Rng.Style <> Styl Then Exit Sub
' expand the range to include preceding paragraphs of same style
Set DocRng = ActiveDocument.Range(0, Rng.End)
With DocRng.Paragraphs
For p = .Count To 1 Step -1
If .Item(p).Range.Style = Styl Then
Rng.MoveStart wdParagraph, -1
Else
Exit For
End If
Next p
End With
' expand the range to include following paragraphs of same style
With ActiveDocument.Paragraphs
For p = (DocRng.Paragraphs.Count + 1) To .Count
If .Item(p).Range.Style = Styl Then
Rng.MoveEnd wdParagraph, 1
Else
Exit For
End If
Next p
End With
Rng.Select
End Subhttps://stackoverflow.com/questions/46294059
复制相似问题