首页 > 解决方案 > 通过 VBA 循环查找匹配项并插入它们而不覆盖以前的结果

问题描述

通常,我使用以下简单的 VBA 代码针对可能的匹配项在 Excel 中持续扫描两个不同的数据集/表,该代码针对工作表 2(辅助表)和工作表 1(主表)中的范围运行它:

Sub loop()

Dim lRow As Long
Dim lCol As Long
Dim lRow2 As Long
Dim lCol2 As Long
Dim wordsArray() as Variant
wordsArray = Worksheets ("SecondaryTable").Range("A2:A" & lRow2).Value
Dim word As Variant
Dim cell As Range

Set sht = Worksheets("MainTable")
Set sht2 = Worksheets("SecondaryTable")

lRow = sht.Range("A1").CurrentRegion.RowsCount
lCol = sht.Range("A1").CurrentRegion.Columns.Count
lRow2 = sht2.Range("A1").CurrentRegion.Rows.Count
lCol2 = sht2.Range("A1").CurrentRegion.Columns.Count

For Each cell in Worksheets("MainTable").Range("I2:I" & lRow)
For Each word in wordsArray
if InStr(cell.Value, word)>0 Then
Cell.Offset (0, -2). Value = word
End if
Next Word
Next Cell

End Sub 

我目前面临的主要问题与通过宏识别多个关键字(例如,两个或三个字符串匹配单元格)导致vba覆盖先前识别的匹配的情况有关。例如,表 2 可能包含作为 wordsArray 一部分的 dog、cat 和 apple,因此包含 Table 中所有这些值/字符串的单元格将仅返回一个并覆盖前两个。有什么方法可以让 VBA 将所有匹配项保存在同一个单元格中?

标签: excelvba

解决方案


推荐阅读