我是单词宏的新手。有人可以向我建议如何在宏中为以下解决方案编写代码。
我需要获取在word文档宏中的文本之间包含特殊符号(“-”)的文本。
这是我们在文字中使用的标题,每个标题也都有序列号
1 test1
2 test2
3 - test3 -
4 test4
5 - test5 -
6 test6
7 - test7 -
8 test8
9 - test9 -
10 test10
11 test11
12 - test12 -
13 test13
14 - test14 -
结果应该像
3 - test3 -
5 - test5 -
7 - test7 -
9 - test9 -
12 - test12 -
14 - test14 -
这是我编写的示例代码,但是在集合中仅获取单个文本“-”时无法正常工作
Public Function GetVariablesFirstLevel() As Collection
On Error GoTo ErrorHandler
Dim objVar As variable
Dim colAux As Collection
Dim strAux As String
Dim objStoryRange As Range
Dim forceExitLoop As Boolean
Set colAux = New Collection
For Each objStoryRange In ActiveDocument.StoryRanges
objStoryRange.Select
Selection.Collapse wdCollapseStart
With Selection
With .Find
.ClearFormatting
.Text = "-"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
forceExitLoop = False
Do While (.Find.Execute And Not forceExitLoop)
strAux = Trim$(Replace$(Right(.Text, 1), vbCr, vbNullString))
If (strAux <> vbNullString) Then
If (Not IsReplacementOfAVariable(strAux)) Then
colAux.Add strAux, UCase$(strAux)
End If
Else
forceExitLoop = True
End If
Loop
End With
Next
Set GetVariablesFirstLevel = colAux
Set colAux = Nothing
Set objStoryRange = Nothing
Exit Function
End Function
答案 0 :(得分:0)
这可能会让您走上正确的轨道。
Public Sub checkHeadings()
Dim d As Word.Document
Dim p As Paragraph
Dim s As String
Set d = ActiveDocument
For Each p In d.Paragraphs
If Not p.Range.Style Is Nothing Then
If Left(p.Range.Style, Len("Heading")) = "Heading" Then
s = fcGetText(p.Range.Text)
If s <> "" Then
Debug.Print s
End If
End If
End If
Next
d.Close
End Sub
Function fcGetText(s As String) As String
Dim arr() As String
arr = Split(s, "-")
If UBound(arr) = 2 Then
fcGetText = s
Else
fcGetText = ""
End If
End Function
答案 1 :(得分:0)
如果在“查找/替换”对话框中(在“查找”->“高级查找”->更多>>”下)选择“使用通配符”,则可以使用星号*
表示任何字符集
因此,此搜索:
Selection.Find.ClearFormatting
With Selection.Find
.Text = "- test* -"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
找到所有候选人。
具有通配符列表,您也可以使用它们进行搜索。