VBA:从字符串中的列表中查找变量

时间:2013-02-28 18:12:59

标签: excel vba excel-vba

我试图查看列表中的某个单词(或数字)是否在某个字符串中。

例如,我有以下短语:“2012年1月20日和2011年” 我试着看看月份是否在句子中,但只要有一个月,句子中的月份就没有关系。 (所以“2012年2月20日和2011年”将会通过)

我在考虑类似的事情:

Sub Run_Find()
Dim Month As String, Number, Year, Splitmonth As Variant
Dim ii As Integer

Month = "January, February, March, April, May, June, July, August, September, October, November, December"
Number = "1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 28, 29, 30, 31"
Year = "2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015"

Splitmonth = VBA.Split(Month, ",")
For ii = 0 To 12
    If VBA.InStr(1, "January 30, 2012 and 2011", Splitmonth(ii)) > 0 Then
        MsgBox "Found it!"
    Else
        MsgBox "Nop!"
    End If
Next ii

End Sub

这很有效。但是有替代方案吗?查看列表,如果列表中的任何单词出现在字符串中,它应该通过。

最后,我试图看到If包含一个月,And一天(数字),And一年,Then ..
使用这种方法似乎“过于复杂”。

提前致谢,R

2 个答案:

答案 0 :(得分:6)

Regular expressions可能会对您有所帮助。正则表达式是一个广泛的主题(),但这里有几个例子就是你的问题。

Public Sub example1()
  Dim re As Object
  Set re = CreateObject("vbscript.regexp")
  re.Pattern = "January|February|March|April|May|June|July|August|September|November|December"
  If re.test("January 30, 2012 and 2011") Then
      Debug.Print "match found"
  End If
End Sub

'=> match found

Public Sub example2()
  Dim re As Object
  Dim matches As Object, match As Object, submatch

  Set re = CreateObject("vbscript.regexp")
  re.Pattern = "(January|February|March|April|May|June|July|August|September|November|December) (\d+), (\d{4})"
  Set matches = re.Execute("January 30, 2012 and 2011")
  For Each match In matches
    Debug.Print "match: " & match
    Debug.Print "submatches: ",
    For Each submatch In match.submatches
        Debug.Print submatch,
    Next
    Debug.Print ""
  Next
End Sub

'=> match: January 30, 2012
'=> submatches:   January       30            2012          

答案 1 :(得分:2)

并不比正则表达式更好,但这是使用过滤器功能的另一种方法

Sub Run_Find()

    Dim sMonth As String
    Dim vaMonth As Variant
    Dim vaDate As Variant
    Dim i As Long

    sMonth = "January, February, March, April, May, June, July, August, September, October, November, December"

    vaMonth = Split(sMonth, "," & Space(1))
    vaDate = Split("July 30, 2012 and 2011", Space(1))

    For i = LBound(vaMonth) To UBound(vaMonth)
        If UBound(Filter(vaDate, vaMonth(i))) >= 0 Then
            Debug.Print vaMonth(i)
            Exit For
        End If
    Next i

End Sub