如何确定Variant是否包含格式文本中的某些文本+数字###

时间:2017-09-15 19:46:02

标签: vba excel-vba powerpoint-vba excel

我在确定iq_Array中存储的Variant / String是否采用我希望的格式时遇到了一些麻烦。我希望我的代码仅在iq_Array = iq_### iq_###时执行,这意味着它必须包含单词iq_,并且必须后跟一个,两个或三个数字。所有这些都很好:

  1. iq_9
  2. iq_99
  3. iq_999
  4. 但是没有:

    1. iq_9,iq_9999
    2. iq_23,iq_5
    3. iq_
    4. iq _3
    5. 任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您应该可以使用通配符#(数字通配符),如下所示:

if iq_Array(i) like "iq_#" Or iq_Array(i) like "iq_##" or iq_Array(i) like "iq_###" then
    ... code ....
end if

如果iq_Array不是字符串,您可以将其包装在Cstr中:Cstr(iq_Array(i))

答案 1 :(得分:0)

您可以使用Split Function

提取元素功能

Function EXTRACTELEMENT(Txt As String, n, Separator As String) As String
 EXTRACTELEMENT = Split(Application.Trim(Txt), Separator)(n - 1)
End Function

代码

如果集合的coll的ele1或ele2是NOK,则该coll不正常,否则就可以了

Dim coll As Collection
Dim i As Long
Dim stemp As String, ele1 As String, ele2 As String

Set coll = New Collection
coll.Add "iq_9"
coll.Add "iq_99"
coll.Add "iq_999"
coll.Add "iq_9,"
coll.Add "iq_23,iq_5"
coll.Add "iq_"
coll.Add "iq _3"

If coll.Count > 0 Then
    For i = 1 To coll.Count
        stemp = stemp & coll(i) & ";"
        ele1 = EXTRACTELEMENT(coll(i), 1, "_")
        ele2 = EXTRACTELEMENT(coll(i), 2, "_")
        valueprint = valueprint & vbNewLine & coll(i) & " ele1: " & ele1 & " ele2: " & ele2 'For Debugging test
        If ele1 = "iq" Then
            Debug.Print vbNewLine & coll(i) & "Ele1 OK"
        Else
            Debug.Print vbNewLine & coll(i) & "Ele1 NOK"
        End If
        If IsNumeric(ele2) = True And InStr(1, ele2, ",") = 0 Then
            Debug.Print vbNewLine & coll(i) & "Ele2 OK"
        Else
            Debug.Print vbNewLine & coll(i) & "Ele2 NOK"
        End If
    Next i

Debug.Print stemp & valueprint

End If

Set coll = Nothing

可选,UDF EXTRACELEMENT的描述

Sub DescribeFunction()
   Dim FuncName As String
   Dim FuncDesc As String
   Dim Category As String
   Dim ArgDesc(1 To 3) As String

   FuncName = "EXTRACTELEMENT"
   FuncDesc = "Returns the nth element of a string that uses a separator character/Retorna o enésimo elemento da string que usa um caractér separador."
   Category = 7 'Text category
   ArgDesc(1) = "String that contains the elements/String que contém o elemento"
   ArgDesc(2) = "Element number to return/ Número do elemento a retornar"
   ArgDesc(3) = "Single-character element separator/ Elemento único separador (spc por padrão)"

   Application.MacroOptions _
      Macro:=FuncName, _
      Description:=FuncDesc, _
      Category:=Category, _
      ArgumentDescriptions:=ArgDesc
End Sub