vba - 填充 Excel 字符串列以实现最快的后续 VBA 搜索的最佳方法(我可以使用元数据等吗?)

标签 vba excel

在包含数百个甚至 1-2000 个大约 40 个字符的字符串的列中,每个单元格一个字符串和许多重复条目,填充列以最快速度执行的最佳方法是什么以后可以搜索吗?搜索应返回行号,以便可以删除相应的行。

是否有某种方法可以将元数据或标签附加到单元格/行以加快搜索速度?是否有其他机制可以识别单元格,从而使搜索变得更容易?

我是 VBA 新手,我想在深入项目并必须搜索数千个字符串之前找到最佳路径。

编辑:有人请求示例单元格:单元格中将包含电子邮件地址。我可以控制服务器上的电子邮件地址,因此每个地址的长度大约为 40 个字符。它们仅包含字母数字字符。

最佳答案

实现字典查找的快速方法示例

  • 数据位于 Sheet1 上,从 A 列开始
  • 字符串位于 B 列
<小时/>
Option Explicit

Public Sub SearchStrings()

    Dim ur As Variant, r As Long, d As Object

    Const COL_ID = 2

    Set d = CreateObject("Scripting.Dictionary") 'or Reference to Microsof Scripting Runtime

    d.CompareMode = TextCompare 'Case insensitive, or "BinaryCompare" otherwise

    ur = Sheet1.UsedRange.Columns(COL_ID)   'read strings from column COL_ID into array

    For r = LBound(ur) To UBound(ur)        'populate dictionary; Key = string (unique)

        If Not IsError(ur(r, 1)) Then d(CStr(ur(r, 1))) = r      'Item = row id

    Next

    Debug.Print d.Keys()(3)     'prints the string in row 3
    Debug.Print d.Items()(3)    'prints the row number of the 3rd string

End Sub
<小时/>

如果你想存储重复的字符串,请使用:

        If Not IsError(ur(r, 1)) Then d(COL_ID & "-" & r) = CStr(ur(r, 1))

其中 Key = 列 ID &“-”& 行 ID (2-5),以及 Item = String本身

关于vba - 填充 Excel 字符串列以实现最快的后续 VBA 搜索的最佳方法(我可以使用元数据等吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45896428/

相关文章:

excel - 为什么我的 Worksheet_Activate 不会触发?

Excel 谷歌地理编码 VBA 错误

algorithm - excel INDEX 未返回预期值

excel - VBA/Excel : Search and filter variable folders within windows explorer, 选择一个文件夹,并导入其文件

excel - VBA:IF 语句中的意外行为。

vba - 打开工作表时自动执行的宏

vba - 对 VBA 代码进行计时返回负时间

arrays - 根据多个条件返回其他工作表中的匹配值

excel - 如何等待 Power Query 刷新完成?

Excel 方法