使用“喜欢”来区分部分相同格式的字符串

时间:2018-07-09 10:38:13

标签: vba excel-vba excel

因此,我们为每个项目创建项目文件。文件名将包含3个值,项目编号,客户名称,采购订单编号。例如; “ 123456-麦当劳-789AB”。现在,项目编号将不会始终存在。表示其已请求或必须被请求。 “麦当劳-789AB”。每个月我都想要一个正在进行中的项目列表(已经有一个项目号)和正在处理中的项目(没有一个项目号)。因此,我创建了一个宏,该宏列出了项目目录中的所有文件。这很完美,但是现在我想列出两种类型的区别列表。问题是,当使用“赞”功能时,扩展字符串的模式在两种类型(客户端名称,采购订单编号)中始终存在,因此只有一个列表正确,而另一个仍然是完整列表。 我正在使用2个匹配功能来做到这一点。

Function Match1(xFile As Object, Index1 As Long, xMatch As Boolean)
xMatch = xFile.Name Like "?*[ ][-][ ]?*"
If xMatch = True Then
  Application.ActiveSheet.Cells(Index1, 1).Formula = xFile.Name
  Index1 = Index1 + 1
End If
xMatch = False
End Function

Function Match2(xFile As Object, Index2 As Long, xMatch As Boolean)
xMatch = xFile.Name Like "######[ ][-][ ]?*[ ][-][ ]?*"
If xMatch = True Then
  Application.ActiveSheet.Cells(Index2 , 6).Formula = xFile.Name
  Index2 = Index2 + 1
End If
xMatch = False
End Function

因此,当匹配“ McDonalds-789AB”时,它将作为这两个功能的匹配项返回。有没有办法使这项工作?为了使操作更容易一些,“项目编号”始终为6位数字。 如果需要更多信息,我可以提供,但是我认为一般问题现在很清楚。

1 个答案:

答案 0 :(得分:0)

这样的事情如何:

Sub matchfile(xFile As Object)

    Dim outputcolumn As Long, myArr

    myArr = Split(xFile.Name, " - ")

    If UBound(myArr) = 2 Then     'if 2, then 3 items are found (0, 1 and 2)
        If myArr(0) Like "######" And myArr(2) Like "###??" Then 
            outputcolumn = 1
        End If
    ElseIf UBound(myArr) = 1 Then     'if 1, then 2 items are found (0 and 1)
        If myArr(1) Like "###??" Then
            outputcolumn = 6
        End If
    End If

    With Application.ActiveSheet
        If outputcolumn > 0 Then .Cells(1 + .Cells(.Rows.Count, 1).End(xlUp).Row, outputcolumn).Formula = xFile.Name
    End With

End Sub

要调用此功能,您只需使用:

matchfile [fileobject]

然后它将用"[ ]-[ ]"分割文件,然后在找到3个项目的位置测试第三个项目是否与"###??"相匹配。在找到2个项目的地方,它仅测试"###??"的第二个项目。如果测试结果是肯定的,它将为outputcolumn分配一个值-根据您的代码判断为1或6,并将文件名写入列outputcolumn中的下一个可用单元格。