从Excel数组中的字符串数组中查找字符串的字符串

时间:2011-07-05 13:11:44

标签: arrays string excel vba vlookup

我在工作簿中有两张Excel工作表。

我在一张表中有参考表。我需要查找单元格中是否存在某个字符串(有一个句子),并在引用表中查找该字符串的值并写入。

这就是我要做的:( Sheet 1是操作表; Sheet 2是参考表。)

VLOOKUP(FIND{"compare","contrast","x",..},from the sheet 1 column 1),if string exists,the value against that string in sheet 2 column 2 written in sheet 2 column 2)

{"compare","contrast"} are all words in sheet 1 column 1

我想比较Sheet 2, Column A中的任何字符串是否与Sheet 1, Column A中的字符串(在句子或字符串数​​组中)匹配。然后,如果它们匹配,则应在Sheet 2, Column 2生成Sheet 1, Column B中字符串的值。

您能指导我如何为此编写宏吗?

1 个答案:

答案 0 :(得分:2)

更新:

这是功能。

它需要2个参数:1st是要搜索的单元格(工作表1,A1),第二个是构成参考表的列(工作表2,A:B)。它将采用Sheet 2 A中的所有术语,并从中创建一个变量数组术语表,其中A列是键,B是值。如果它找到单元格中的一个字符串,它会将它放在一个名为result的新字符串中。作为个人选择,我将glossay设置为静态,以便在您同时在多个单元格上运行此功能时运行速度更快,但如果您愿意,可以将其更改为Dim。

所以对于A1,你会写:

=FindString(A1,Sheet2!A:B)

这是代码,请尝试一下,我希望它有所帮助,或者至少给你一个良好的开端。

Function FindString(ByVal text As String, _
                    ByVal term_list As range) As String

Dim result As String
Dim i As Long
Static glossary As Variant
glossary = range(term_list.Cells(1, 1).End(xlDown), term_list.Cells(1, 2))

For i = 1 To UBound(glossary)
    If InStr(text, glossary(i, 1)) <> 0 Then
       result = (glossary(i, 1) & " = ") & (glossary(i, 2) & vbLf) & result
    End If
Next

If Len(result) <> 0 Then
    result = Left$(result, (Len(result) - 1))
End If

FindString = result

End Function
相关问题