【问题标题】:VBA/ Excel method for searching/ matching 60+ values in a single cellVBA/ Excel 方法用于在单个单元格中搜索/匹配 60 多个值
【发布时间】:2015-01-19 08:34:13
【问题描述】:

我正在too系统之间进行迁移。旧系统使用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,所以任何示例/指针都将不胜感激。

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    是否有其他方法使用 Excel 函数或者我必须使用 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
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多