VBA/ Excel 在单个单元格中搜索/匹配 60 多个值的方法

VBA/ Excel method for searching/ matching 60+ values in a single cell

我正在太系统之间进行迁移。旧系统使用Tags对商品进行分类,新系统引入Type。

我可以使用加载到 Excel 中的几千行 CSV 格式的数据。这是格式示例。

Col A      | Col B | Col C
Product    | Type  | Tags
Samsung S5 |       | Android, Samsung, 5.1" Screen
Sony Z3    |       | Android, Bluetooth, Sony, 5.2" Screen
LG G3      |       | Android, LG, 5.5" Screen

我希望能够使用 C 列中的单个标记填充 B 列。我可以这样做:

A1: =IF(SEARCH("Sony",B2),"Sony", IF(SEARCH("Samsung",B2),"Samsung",etc))

但是我想将 C 列中的 60 多个单独的标签搜索/匹配到 B 列中的单个值中,因此这种方法很快变得难以管理。

是否有另一种使用 Excel 函数的方法,或者我是否必须使用 VBA?

我已经很多年没用过 VBA 了,所以任何示例/指示都将不胜感激。

Is there another approach using Excel functions or would I have to use VBA?

恕我直言 VBA,试试这个:

  1. 第一个变体(比第二个变体慢)

    Sub test()
    Dim oCellTag As Range, oCellSource As Range
    For Each oCellTag In Sheets("Tags").Range("A1:A3") 'Range with Tags in one sheet
        For Each oCellSource In Sheets("Source").Range("C2:C4") 'Range with data for search tags in another sheet
            If UCase(oCellSource.Value) Like "*" & UCase(oCellTag.Value) & "*" And oCellTag.Value <> "" Then 'if cell contain tag
                Sheets("Source").Cells(oCellSource.Row, oCellSource.Column - 1).Value = oCellTag.Value
            End If
        Next
    Next
    End Sub
    
  2. 第二种变体(快速)

    Sub test2()
    Dim oCellTag As Range, oCellSource As Range, KeySource, KeyTag
    Dim Source As Object: Set Source = CreateObject("Scripting.Dictionary")
    Dim Tags As Object: Set Tags = CreateObject("Scripting.Dictionary")
    'Grab the dates from the WorkSheets
    For Each oCellTag In Sheets("Tags").Range("A1:A3")
        If oCellTag.Value <> "" Then
            Tags.Add oCellTag.Row, oCellTag.Value
        End If
    Next
    For Each oCellSource In Sheets("Source").Range("C2:C4")
        If oCellSource.Value <> "" Then
            Source.Add oCellSource.Row, oCellSource.Value
        End If
    Next
    'Match
    For Each KeyTag In Tags
        For Each KeySource In Source
            If UCase(Source(KeySource)) Like "*" & UCase(Tags(KeyTag)) & "*" Then
                Sheets("Source").Cells(KeySource, 2).Value = Tags(KeyTag)
            End If
        Next
    Next
    End Sub