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

MeR*_*uud 3 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
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢你,R

A. *_*ebb 6

正则表达式在这里可能会有用.正则表达式是一个广泛的主题(),但这里有几个问题的例子.

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          
Run Code Online (Sandbox Code Playgroud)