检查字符串中文件扩展名的最佳方法是什么?

时间:2018-02-11 14:20:01

标签: excel vba excel-vba

我有一个报告,其中每行中的一个单元格包含连接到特定帐户的每个文件的名称(w /扩展名)。我们正在寻找一些组合,其余组合被认为无效,并要求我们通过电子邮件向帐户持有人发送电子邮件。我目前只是通过使用Like运算符的If Then语句来检查文件类型是否存在(例如,如果单元格(i,11).value2类似于“ .xls ”那么),或者,如果有超过1,一个检查特定文件扩展名出现次数的函数。

目前我能够解析并找到特定的文件类型,但我无法明确告诉特定文件类型与哪个相关,除非我检查它的正确组合,这需要一大堆条件我是投注可以添加到列表或其他内容并进行检查。如果它有帮助,则“联系人”的值不同,需要使用不同的组合进行检查。

请参阅下面我当前代码的示例:

If (cells(i,10).value2 = "Contacts" Then 'Checking if one exists

   If (cells(i,11).value2 Like "*.pdf*" or cells(i,11).value2 Like "*.mht*") and (not cells(i,11).value2 like "*.msg*" or not cells(i,11).value2 like "*.oft*") Then
       cells(i,12).value2 = "Incorrect email uploaded"

   ElseIf (cells(i,11).value2 Like "*.zip*" or cells(i,11).value2 Like "*.rar*") and (not cells(i,11).value2 like "*.msg*" or not cells(i,11).value2 like "*.oft*") and (cells(i,11).value2 like "*.xls*" or cells(i,11).value2 like "*.doc*" Then
       cells(i,12).value2 = "Probably missing email"

   ElseIf (not cells(i,11).value2 Like "*.msg*" and not cells(i,11).value2 Like "*.oft*") and cells(i,11).value2 like "*.doc*" Then
        cells(i,12).value2 = "Missing email"

   ElseIf (cells(i,11).value2 Like "*.msg*" or cells(i,11).value2 Like "*.oft*") and not cells(i,11).value2 like "*.doc*" Then
        cells(i,12).value2 = "Missing contacts document"

   End If
End If

 If (cells(i,10).value2 = "Contacts" Then 'Checking if two exist

   If StrOcc(cells(i,11).value2, ".msg") < 2 or StrOcc(cells(i,11).value2, ".oft") < 2 Then
       cells(i,12).value2 = "Missing 1 email uploaded"

   End If
 End If

Function StrOcc(text as String, checkedagainst as substring)
  if instr(...

1 个答案:

答案 0 :(得分:1)

这可能更容易使用:

If Cells(i, 10).Value2 = "Contacts" Then 'Checking if one exists

    Dim str As String, email1 As Long, email2 As Long
    Dim pdf_mht As Boolean, zip_rar As Boolean, doc As Boolean, xls_doc As Boolean

    str = Cells(i, 11).Value2

    email1 = UBound(Split(str, ".msg"))
    email2 = UBound(Split(str, ".oft"))

    pdf_mht = UBound(Split(str, ".pdf")) > 0 And UBound(Split(str, ".mht")) > 0
    zip_rar = UBound(Split(str, ".zip")) > 0 And UBound(Split(str, ".rar")) > 0

    doc = UBound(Split(str, ".doc")) > 0
    xls_doc = UBound(Split(str, ".xls")) > 0 And doc

    If email1 = 0 And email2 = 0 Then
        Cells(i, 12).Value2 = "Missing email"
    ElseIf email1 = 0 Or email2 = 0 Then
        If pdf_mht Then
            Cells(i, 12).Value2 = "Incorrect email uploaded"
        ElseIf zip_rar And xls_doc Then
            Cells(i, 12).Value2 = "Probably missing email"
        ElseIf doc Then
            Cells(i, 12).Value2 = "Missing contacts document"
        End If
    ElseIf email1 < 2 Or email2 < 2 Then
        Cells(i, 12).Value2 = "Missing 1 email uploaded"
    End If
End If

(未测试的)