vba - 将单元格内的任何单词与单元格范围内的任何单词相匹配

标签 vba excel excel-formula udf

我有一个短语列表。我想检查是否有任何新术语与该列表部分单词匹配。

我正在寻找一个代码来在列表上实现模糊匹配,以返回具有紧密匹配的单元格。

示例数据:

enter image description here

Phrases,Terms
real term,new words
great work,new term
check phrase,more phrase
example here,great alpha
phrase random,beta new

所需输出:

enter image description here

Phrases,Term,Match
real term,new words,No match
great work,new term,real term
check phrase,more phrase,check phrase/phrase random
example here,great alpha,great work
phrase random,beta new,No match

我所拥有的:

我尝试使用以下代码来匹配单元格(如果找到):

=IF(ISERROR(MATCH("*" & B2 & "*",A:A, 0)), "No Match", VLOOKUP("*" & B2 & "*",A:A,1,FALSE))

但是,代码仅匹配整个单元格。我怎样才能让它匹配单元格中的任何单词?这将创建模糊匹配。任何积极的投入都会受到高度赞赏。

最佳答案

这是针对您的问题的(粗略且现成的)VBA 解决方案。您需要将其插入到 VBA 编辑器中的代码模块中,然后可以运行宏来获得所需的输出

Sub FindSimilar()
    Dim phrases As Range, phrase As Range
    Dim terms As Range, term As Range
    Dim matches As String
    Dim words() As String

    'ensure this has the correct sheet names for your workbook
    Set phrases = ThisWorkbook.Worksheets("Sheet2").Range("A2:A6")
    Set terms = ThisWorkbook.Worksheets("Sheet1").Range("D2:D6")

    For Each term In terms
        matches = vbNullString
        words() = Split(term.Value)

        For i = 0 To UBound(words, 1)
            For Each phrase In phrases
                If InStr(1, phrase.Value, words(i)) Then
                    matches = matches & phrase & "/"
                End If
            Next phrase
        Next i

        If matches <> vbNullString Then
            term.Offset(0, 5).Value = Left(matches, Len(matches) - 1)
        Else
            term.Offset(0, 5).Value = "No match"
        End If
    Next term
End Sub

关于vba - 将单元格内的任何单词与单元格范围内的任何单词相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40661523/

相关文章:

excel - OpenXML - 单元格更新后刷新 Excel 工作表

vba - 关于在工作簿中搜索特定日期并在该日期之前设置预先通知?

excel - VBA - 无法找到 accdb 格式的提供程序

javascript - 将excel公式转换为JS?

excel - 与 =IFERROR(IF(VALUE.. 与 2 个电话号码列进行比较

excel - 更改excel中的日期格式

具有相对引用的 Excel 命名范围不计算

excel - 取消选择表单控件列表框中的所有项目

vba - 从用户窗体 VBA 存储变量

Python-excel-xlwt : colouring every second row