我有一个代码,可以找到单元格注释中是否有特定单词。但是,我希望它查看单独的行。在range(“ A1:A10”)中,有些单元格有注释,其余的没有注释,有些注释看起来像这样
Fruit1: Apple
Fruit2: Orange
Fruit3: Banana
其他人看起来像这样
Fruit1: Apple / Green apple
Fruit2: Orange
Fruit3: Banana / Kiwi
使用我当前的代码,当我搜索“香蕉”时,这2条评论将出现在立即窗口中,但是,我只希望它返回第一个评论。以下是我为此做的尝试
Sub testlike()
Dim c As Range, rng As Range, cell As Range
Dim fruit As String
fruit = "Banana" 'Is going to be an input msgbox but for testing purposes, i left it at "Banana"
Set rng = Range("A1:F10")
For Each cell In rng
Set c = cell.Find(fruit, LookIn:=xlComments)
If Not c Is Nothing Then
Debug.Print c.Comment.Text
End If
Next cell
End Sub
我对vba还是比较陌生,所以如果我看上去很愚昧,我深表歉意。预先感谢!
答案 0 :(得分:1)
像这样吗?
Sub testlike()
Dim rng As Range, cell As Range
Dim arr As Variant
Dim x As Long
Dim fruit As String
fruit = "Banana" 'Is going to be an input msgbox but for testing purposes, i left it at "Banana"
Set rng = Range("A1:F10").SpecialCells(xlCellTypeComments)
For Each cell In rng
arr = Split(cell.Comment.Text, Chr(10))
For x = LBound(arr) To UBound(arr)
If arr(x) Like "*: " & fruit Then
Debug.Print cell.Comment.Text
Exit For
End If
Next x
Next cell
End Sub
这是假定:
Fruit1: Apple
Fruit2: Orange
Fruit3: Banana
是一个评论吗?...还是我误会了?
答案 1 :(得分:0)
如果您只对第一个匹配感兴趣,则可以在找到它之后直接退出for循环:
Sub testlike()
Dim c As Range, rng As Range, cell As Range
Dim fruit As String
fruit = "Banana" 'Is going to be an input msgbox but for testing purposes, i left it at "Banana"
Set rng = Range("A1:F10")
For Each cell In rng
Set c = cell.Find(fruit, LookIn:=xlComments)
If Not c Is Nothing Then
Debug.Print c.Comment.Text
Exit for ' <-- this will exit the for loop
End If
Next cell
End Sub