Excel VBA:如果字符串数组中存在该单词,则将“字符串中的单词”存储到变量中

时间:2015-06-29 13:30:07

标签: excel vba excel-vba

假设我的字符串是

my_string="MY PET IS CAT "

我还有一个数组

my_animals=Array ("CAT","DOG","LION")

由于my_string中有一个数组中的字符串(CAT),我希望在变量中包含CAT。

我们怎样才能成功?

2 个答案:

答案 0 :(得分:2)

Dim my_string As String, my_animals As Variant, element As Variant, variable as String
my_string = "MY PET IS CAT "

my_animals = Array("CAT", "DOG", "LION")

For Each element In my_animals
  If InStr(my_string, element) Then
  variable = element
  End If
Next element

答案 1 :(得分:2)

仅供后人使用my_animals中添加 my_string 元素的方式(不是特别精彩,但功能齐全):

Public Sub FindAnimals

    dim my_string as String
    dim my_animals as Variant
    dim found(0) as String
    dim animal as String

    my_string="MY PETS ARE CAT AND LION"
    my_animals=Array ("CAT","DOG","LION")

    For Each animal in my_animals
       If InStr(my_string, animal) Then
           found(UBound(found)) = animal
           ReDim Preserve found(UBound(found) + 1)
       End If
    Next animal

End Sub

运行后,found将是一个包含三个元素的String数组:

  • "CAT"
  • "LION"
  • ""

正如我所说,它不是世界上最好的方法,但它可能是一个更好的起点。