如何在列中搜索特定单词并将其返回到同一行而是另一个单元格?

时间:2017-01-15 13:17:20

标签: vba excel-vba excel

我已经将G3和H3值返回到M3和N3单元格。 我想要的是从单元格(J3)中只找到1个特定单词,如“chocolate”并将其返回到单元格(M3)

有没有办法编写Excel宏来查找列(G)中列(G)中列出的那些特定单词,如果列(J)包含那些特定单词,宏只返回到列(M)的特定单词到同一个单词排它被发现。 (但另一个单元格,如屏幕截图中的M3)

Excel Macro Screenshot

Private Sub CommandButton1_Click()
Dim score1 As String, score2 As Integer, result1 As String, result2 As String

score1 = Range("G3").Value
score2 = Range("H3").Value

If score1 = "chocolate" Then
result1 = "chocolate"
result2 = "4"
Else
result1 = "" And result2 = ""
End If

Range("M3").Value = result1
Range("N3").Value = result2

End Sub

它正在使用Range(仅一个单元格)。

但是如何搜索在列(“J:J”)中找到的列(“G3:G7”)中列出的特定单词以及何时找到将特定单词返回到列(“M”)的单词排它被发现。

所以我可以按OK! CommandButton和如果Column(“J:J”)包含Column(“G:G”)中的任何单词,将从Column(“G:G”)中找到的“找到”的确切单词将插入到Column(“M:M”)中到找到它的同一行。

我尝试过简单的功能:

=IF(ISNUMBER(SEARCH($G$3;"*"&A:A&"*"));"chocolate";IF(ISNUMBER(SEARCH($G$4;"*"&A:A&"*"));"muffin";IF(ISNUMBER(SEARCH($G$5;"*"&A:A&"*"));"lemon";IF(ISNUMBER(SEARCH($G$6;"*"&A:A&"*"));"monkey";IF(ISNUMBER(SEARCH($G$7;"*"&A:A&"*"));"baby")))))

=IF(ISERROR(SEARCH(D3;"*"&A3&"*";A3));B3;"")

它正如您在下面看到的那样工作,但宏会更容易。
Not macro but working

1 个答案:

答案 0 :(得分:0)

在OP的澄清后编辑

Option Explicit

Private Sub CommandButton1_Click()
    Dim cell As Range
    Dim words As Variant
    Dim word As String, number As Long

    words = Range("H3", Cells(Rows.Count, "G").End(xlUp)).value

    For Each cell In Range("J3", Cells(Rows.Count, "J").End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues)
        If FindWord(cell.value, words, word, number) Then
            cell.Offset(, 3).Resize(, 2).value = Array(word, number)
        End If
    Next
End Sub

Function FindWord(sentence As String, words As Variant, returnedWord As String, returnedNumber As Long) As Boolean
    Dim iWord As Long
    Dim word As String

    For iWord = LBound(words, 1) To UBound(words, 1)
        word = CStr(words(iWord, 1))
        If InStr(sentence, word) Then
            FindWord = True
            returnedWord = word
            returnedNumber = CLng(words(iWord, 2))
            Exit Function
        End If
    Next
End Function