【发布时间】:2016-02-17 21:44:10
【问题描述】:
我正在尝试为突出显示和搜索的单词添加计数,到目前为止,我将 icount 添加为字符串,它有时最多计数为 1,有时为 2,我认为我的公式可能是错误的,而且我的室友也擅长 c并认为我应该将 icount 作为字符串更改为长整数或整数。
Sub highlightext()
Application.ScreenUpdating = False
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
Dim oRange As Range
Set oRange = ws.Cells
Dim wordToFind As String
wordToFind = InputBox(Prompt:="What word would you like to highlight?")
Dim cellRange As Range
Set cellRange = oRange.Find(What:=wordToFind, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not cellRange Is Nothing Then
Dim Foundat As String
Foundat = cellRange.Address
Set outws = Worksheets("product")
outws.Range("A2").Value = wordToFind
Do
Dim textStart As Integer
textStart = 1
Do
textStart = InStr(textStart, LCase(cellRange.Value), LCase(wordToFind))
If textStart <> 0 Then
cellRange.Characters(textStart, Len(wordToFind)).Font.Color = RGB(250, 0, 0)
textStart = textStart + 1
End If
Loop Until textStart = 0
Set cellRange = oRange.FindNext(After:=cellRange)
Loop Until cellRange Is Nothing Or cellRange.Address = Foundat
End If
Dim icount() As String
icount = Split(Foundat, ", ")
outws.Range("B2").Value = UBound(icount) + 1
End Sub
【问题讨论】:
-
你需要通过逐行运行代码来调试这个[反复按f8]。我不知道你想用代码的 cellRange2 部分做什么,但我怀疑它正在做你想做的事。似乎循环的顺序不正确,或者其他什么。但是 - 要求我们做你自己没有做过的调试太过分了。
-
在你的最后一个
For each cell in oRange循环中,将oRange更改为Range(Foundat),你将是金色的(或者至少我的测试是金色的.. 或者是红色的 :))。您想遍历实际找到匹配项的地址范围,而不是再次遍历 A 列的整个范围。否则,您将按字面意思突出每个单元格的前 5 个字符,因为wordToFind未找到,因为Instr将为 0。 -
您是否希望代码仅在单元格中为
wordToFind的第一个 实例着色?? -
有点工作,如果单元格中有“wordtofind”,它会突出显示句子中的第一个单词,但不会突出显示单词本身,不会通读句子@ScottHoltzman
-
这很有趣@Dayday。我在文本的开头/中间/结尾处使用了一个单词进行了测试,它按照您的要求将它们全部突出显示 - 只有 actual 单词被突出显示。