我试图将“出现次数”写成红色或加粗红色。有人能指出我正确的方向吗?我是编码新手。这是一个字计数器,当找到2个以上的单词时...会在单词文档的底部显示找到的单词数。
Sub a3()
Dim Word As String
Dim wcount As Integer
Word = InputBox("Search for a word")
If (Word <= "") Then
MsgBox ("Did not enter word")
End If
If (Word > "") Then
wcount = 0
With Selection
.HomeKey Unit:=wdStory
With ActiveDocument.Content.Find
.Text = Word
Do While .Execute
wcount = wcount + 1
Selection.MoveRight
Loop
End With
MsgBox ("The word: '" & Word & "' shows up " & wcount & " times in the document")
End With
End If
If (wcount <= 2) Then
ActiveDocument.Content.InsertAfter Text:=(vbCrLf & "Number occurrences: " & wcount)
Selection.Font.ColorIndex = wdRed
ElseIf (wcount <= 3) Then
ActiveDocument.Content.InsertAfter Text:=(vbCrLf & "Number occurrences: " & wcount)
Selection.Font.ColorIndex = wdRed
Selection.Font.Bold = True
Else
ActiveDocument.Content.InsertAfter Text:=(vbCrLf & "Number occurrences: " & wcount)
Selection.Font.ColorIndex = wdBlack
Selection.Font.Bold = False
End If
End Sub
答案 0 :(得分:0)
使用Word (ns tst.tupelo.forest-examples
(:use tupelo.core tupelo.forest tupelo.test)
...)
对象将对此有所帮助。将backface-visibility: hidden
视为一个不可见的选择,不同之处在于代码可以与多个Range
对象一起工作,而只能有一个Range
对象。
将文档的内容分配给Range
,然后在其上执行Selection
和扩展名。然后,格式也可以应用于Range
。我已更改(但未测试)问题中的代码以进行演示。
在最后一部分中,在文档末尾写有文本的地方,Find
对象被设置为整个文档,然后折叠起来(想像它就像选择了选择向右箭头键一样) 。然后,将新文本分配给所应用的范围和格式。由于范围将仅包含新文本,因此仅将格式应用于该文本。
(附加说明:我将Range
变量名更改为Range
,因为“ Word”可能被误认为是Word应用程序。我还更改了比较以检查{{ 1}}中包含Word
,因为不能保证“大于”比较。)
sWord
答案 1 :(得分:0)
有很多方法可以做到这一点,其中一些是基于对范围或选择的偏好以及Find语句的结构。这是我的偏好。
Sub a3()
Dim wrd As String
Dim wcount As Integer
Dim rng As Word.Range
wrd = InputBox("Search for a word")
If wrd = vbNullString Then
MsgBox ("Did not enter word")
Exit Sub
End If
Set rng = ActiveDocument.Content
wcount = 0
With rng.Find
.ClearFormatting
.Format = False
.Forward = True
.MatchWholeWord = True
.Text = wrd
.Wrap = wdFindStop
.Execute
Do While .found
wcount = wcount + 1
rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
.Execute
Loop
End With
MsgBox ("The word: " & "" & wrd & "" & " shows up " & wcount & " times in the document")
ActiveDocument.Content.InsertParagraphAfter
Set rng = ActiveDocument.Content
rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
rng.Text = "Number occurrences: " & wcount
If wcount < 3 Then
rng.Font.ColorIndex = wdRed
ElseIf wcount < 4 Then
rng.Font.ColorIndex = wdRed
rng.Font.Bold = True
Else
rng.Font.ColorIndex = wdAuto
rng.Font.Bold = False
End If
End Sub