If file name contains specific text then execute

26,311

The problem is that there is no space in the words in the file names. In such a scenario it becomes difficult to prevent False Positives.

Having said that if the text that you are looking for will always be between 2 numbers; for example Agreement is between 20170614 and 01 in 20170614Agreement01_MSD.xls then we may take this approach

Add this function to your code

Private Function getTextBtwnNumbers(s As String) As String
    Dim pos1 As Long, pos2 As Long
    Dim i As Long, j As Long

    For i = 1 To Len(s)
        If pos1 = 0 Then
            Select Case Asc(Mid(s, i, 1))
            Case 65 To 90, 97 To 122
                pos1 = i
            End Select
        Else
            For j = pos1 To Len(s)
                Select Case Asc(Mid(s, j, 1))
                Case 65 To 90, 97 To 122
                Case Else
                    pos2 = j ' - 1
                    Exit For
                End Select
            Next j
        End If

        If pos1 <> 0 And pos2 <> 0 Then Exit For
    Next i

    If pos1 <> 0 And pos2 <> 0 Then
        getTextBtwnNumbers = Trim(Mid(s, pos1, pos2 - pos1))
    Else
        getTextBtwnNumbers = "Invalid Text Format"
    End If
End Function

And then you can use it like this

Sub Sample()
    Dim flName As String

    flName = "20170614Agreement01_MSD.xls"

    If getTextBtwnNumbers(flName) = "Agreement" Then
        MsgBox "Match Found"
    End If
End Sub

Note:

I am assuming that the text will be between 2 numbers in the format NumberTEXTNumber.

If you have a format which is NumberTEXTONENumberTEXTTWONumber then the function will only extract TEXTONE

EDIT

I realised that there is a better way using LIKE. This way you will not need the above function.

Sub Sample()
    Dim flName As String, Searchtext As String

    flName = "20170614Agreement01_MSD.xls"

    Searchtext = "Agreement"

    If flName Like "*#" & Searchtext & "#*.xls" Then MsgBox "Match Found"
End Sub
Share:
26,311

Related videos on Youtube

Philip Connell
Author by

Philip Connell

Did this for the Badge cant believe I am getting addicted to this site :-)

Updated on September 03, 2020

Comments

  • Philip Connell
    Philip Connell over 3 years

    I have code that loops through a folder and adds text values to G1, H1, I1 etc etc. to Workbooks.

    In Pic 1 you see I have several files in my folder. Different Excel files or Workbooks get different Text Values added to them.

    The Text Values to be added to the "Professional" Workbook are different from the Text Values to be added to "ProfessionalAddress" or "ProfessionalCommunication".

    I have tried to use InStr but this will take any file name that contains a certain piece of text.
    For example I have several files that contain the word "Professional" this means that the code then adds the text values for "Professional" file to all files that contain the text "Professional".

    I need when a file name contains "Professional" add these Text Values, when a file contains "ProfessionalAddress" add these Text Values. Likewise for "Meeting" "Organization" "Customer".

    Pic 1 enter image description here

    Sub LoopAllExcelFilesInFolder()
    'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
    'SOURCE: www.TheSpreadsheetGuru.com
    
    Dim wb As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim FldrPicker As FileDialog
    
    'Optimize Macro Speed
      Application.ScreenUpdating = False
      Application.EnableEvents = False
      Application.Calculation = xlCalculationManual
    
    'Retrieve Target Folder Path From User
      Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    
        With FldrPicker
          .Title = "Select A Target Folder"
          .AllowMultiSelect = False
            If .Show <> -1 Then GoTo NextCode
            myPath = .SelectedItems(1) & "\"
        End With
    
    'In Case of Cancel
    NextCode:
      myPath = myPath
      If myPath = "" Then GoTo ResetSettings
    
    'Target File Extension (must include wildcard "*")
      myExtension = "*.xls*"
    
    'Target Path with Ending Extention
      myFile = Dir(myPath & myExtension)
    
    'Loop through each Excel file in folder
      Do While myFile <> ""
        'Set variable equal to opened workbook
          Set wb = Workbooks.Open(Filename:=myPath & myFile)
    
        'Ensure Workbook has opened before moving on to next line of code
          DoEvents
    
                If InStr(myFile, "Professional") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "ProfessionalId"
          Range("J1").Value = "StatusCode"
          Range("K1").Value = "ProfessionalTypeCode"
          Range("L1").Value = "StatusDate"
          Range("M1").Value = "Qualification"
          Range("N1").Value = "ProfessionalSubtypeCode"
          Range("O1").Value = "FirstName"
          Range("P1").Value = "MiddleName"
          Range("Q1").Value = "LastName"
          Range("R1").Value = "SecondLastName"
          Range("S1").Value = "MeNumber"
          Range("T1").Value = "ImsPrescriberId"
          Range("U1").Value = "NdcNumber"
          Range("V1").Value = "TitleCode"
          Range("W1").Value = "ProfessionalSuffixCode"
          Range("X1").Value = "GenderCode"
          Range("Y1").Value = "Reserved for future use"
          Range("Z1").Value = "Reserved for future use"
          Range("AA1").Value = "Reserved for future use"
          Range("AB1").Value = "Reserved for future use"
          Range("AC1").Value = "SourceDataLevelCode"
          Range("AD1").Value = "PatientsPerDay"
          Range("AE1").Value = "PrimarySpecialtyCode"
          Range("AF1").Value = "SecondarySpecialtyCode"
          Range("AG1").Value = "TertiarySpecialtyCode"
          Range("AH1").Value = "NationalityCode"
          Range("AI1").Value = "TypeOfStudy"
          Range("AJ1").Value = "UniversityAffiliation"
          Range("AK1").Value = "SpeakerStatusCode"
          Range("AL1").Value = "OneKeyId"
          Range("AM1").Value = "NucleusId"
          Range("AN1").Value = "Suffix"
          Range("AO1").Value = "ClientField1"
          Range("AP1").Value = "ClientField2"
          Range("AQ1").Value = "ClientField3"
          Range("AR1").Value = "ClientField4"
          Range("AS1").Value = "ClientField5"
          Range("AT1").Value = "Reserved for future use"
          Range("AU1").Value = "NPICountry"
          Range("AV1").Value = "CountryCode"
          Range("AW1").Value = "Reserved for future use"
          Range("AX1").Value = "MassachusettsId"
          Range("AY1").Value = "NPIId"
          Range("AZ1").Value = "UniversityCity"
          Range("BA1").Value = "UniversityPostalArea"
    
        End If
    
        If InStr(myFile, "ProfessionalAddress") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "ProfessionalAddressId"
          Range("J1").Value = "EffectiveDate"
          Range("K1").Value = "StatusCode"
          Range("L1").Value = "ProfessionalId"
          Range("M1").Value = "AddressTypeCode"
          Range("N1").Value = "StatusDate"
          Range("O1").Value = "Reserved for future use"
          Range("P1").Value = "AddressLine1"
          Range("Q1").Value = "AddressLine2"
          Range("R1").Value = "AddressLine3"
          Range("S1").Value = "City"
          Range("T1").Value = "State"
          Range("U1").Value = "PostalArea"
          Range("V1").Value = "PostalAreaExtension"
          Range("W1").Value = "CountryCode"
          Range("X1").Value = "Reserved for future use"
          Range("Y1").Value = "Reserved for future use"
          Range("Z1").Value = "Reserved for future use"
          Range("AA1").Value = "DeaNumber"
          Range("AB1").Value = "DeaExpirationDate"
          Range("AC1").Value = "LocationName"
          Range("AD1").Value = "EndDate"
          Range("AE1").Value = "N/A"
    
        End If
    
        If InStr(myFile, "ProfessionalStateLicense") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "ProfessionalLicenseId"
          Range("J1").Value = "EffectiveDate"
          Range("K1").Value = "EndDate"
          Range("L1").Value = "ProfessionalId"
          Range("M1").Value = "StateLicenseNumber"
          Range("N1").Value = "StateLicenseState"
          Range("O1").Value = "StateLicenseExpirationDate"
          Range("P1").Value = "SamplingStatusCode"
          Range("Q1").Value = "Reserved for future use"
          Range("R1").Value = "N/A"
    
        End If
    
    
         If InStr(myFile, "ProfessionalCommunication") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "ProfessionalCommunicationId"
          Range("J1").Value = "ProfessionalId"
          Range("K1").Value = "CommunicationTypeCode"
          Range("L1").Value = "CommunicationValue1"
          Range("M1").Value = "CommunicationValue2"
          Range("N1").Value = "ProfessionalAddressId"
          Range("O1").Value = "N/A"
    
        End If
    
          If InStr(myFile, "Organization") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "OrganizationId"
          Range("J1").Value = "StatusCode"
          Range("K1").Value = "OrganizationTypeCode"
          Range("L1").Value = "StatusDate"
          Range("M1").Value = "Reserved for future use"
          Range("N1").Value = "OrganizationSubtypeCode"
          Range("O1").Value = "OrganizationName"
          Range("P1").Value = "NPICountry"
          Range("Q1").Value = "Reserved for future use"
          Range("R1").Value = "Reserved for future use"
          Range("S1").Value = "Reserved for future use"
          Range("T1").Value = "Reserved for future use"
          Range("U1").Value = "SourceDataLevelCode"
          Range("V1").Value = "Reserved for future use"
          Range("W1").Value = "Reserved for future use"
          Range("X1").Value = "OneKeyId"
          Range("Y1").Value = "FederalTaxId"
          Range("Z1").Value = "Reserved for future use"
          Range("AA1").Value = "NucleusId"
          Range("AB1").Value = "Reserved for future use"
          Range("AC1").Value = "ClientField1"
          Range("AD1").Value = "ClientField2"
          Range("AE1").Value = "ClientField3"
          Range("AF1").Value = "ClientField4"
          Range("AG1").Value = "ClientField5"
          Range("AH1").Value = "MassachusettsId"
          Range("AI1").Value = "NPIId"
          Range("AJ1").Value = "N/A"
    
        End If
    
          If InStr(myFile, "OrganizationAddress") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "OrganizationAddressId"
          Range("J1").Value = "EffectiveDate"
          Range("K1").Value = "StatusCode"
          Range("L1").Value = "OrganizationId"
          Range("M1").Value = "AddressTypeCode"
          Range("N1").Value = "StatusDate"
          Range("O1").Value = "Reserved for future use"
          Range("P1").Value = "AddressLine1"
          Range("Q1").Value = "AddressLine2"
          Range("R1").Value = "AddressLine3"
          Range("S1").Value = "City"
          Range("T1").Value = "State"
          Range("U1").Value = "PostalArea"
          Range("V1").Value = "PostalAreaExtension"
          Range("W1").Value = "CountryCode"
          Range("X1").Value = "Reserved for future use"
          Range("Y1").Value = "Reserved for future use"
          Range("Z1").Value = "Reserved for future use"
          Range("AA1").Value = "DeaNumber"
          Range("AB1").Value = "DeaExpirationDate"
          Range("AC1").Value = "LocationName"
          Range("AD1").Value = "EndDate"
          Range("AE1").Value = "N/A"
    
        End If
    
          If InStr(myFile, "OrganizationCommunication") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "OrganizationCommunicationId"
          Range("J1").Value = "OrganizationId"
          Range("K1").Value = "CommunicationTypeCode"
          Range("L1").Value = "CommunicationValue1"
          Range("M1").Value = "CommunicationValue2"
          Range("N1").Value = "OrganizationAddressId"
          Range("O1").Value = "N/A"
    
        End If
    
         If InStr(myFile, "OrganizationSpecialty") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "OrganizationSpecialtyId"
          Range("J1").Value = "OrganizationId"
          Range("K1").Value = "SpecialtyTypeCode"
          Range("L1").Value = "SpecialtyCode"
          Range("M1").Value = "N/A"    
    
        End If
    
          If InStr(myFile, "Agreement01_MSD") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "AgreementId"
          Range("J1").Value = "CompanyId"
          Range("K1").Value = "AgreementName"
          Range("L1").Value = "AgreementType"
          Range("M1").Value = "StatusCode"
          Range("N1").Value = "Description"
          Range("O1").Value = "AgreementDate"
          Range("P1").Value = "CustomerId"
          Range("Q1").Value = "ApprovalDate"
          Range("R1").Value = "StartDate"
          Range("S1").Value = "EndDate"
          Range("T1").Value = "SignatureDate"
          Range("U1").Value = "SecondaryCustomerId"
          Range("V1").Value = "AgreementCountry"
          Range("W1").Value = "ClientField1"
          Range("X1").Value = "ClientField2"
          Range("Y1").Value = "ClientField3"
          Range("Z1").Value = "ClientField4"
          Range("AA1").Value = "ClientField5"
          Range("AB1").Value = "ClientDate1"
          Range("AC1").Value = "ClientDate2"
          Range("AD1").Value = "ClientNumber1"
          Range("AE1").Value = "ClientNumber2"
          Range("AF1").Value = "DataSourceId"
          Range("AG1").Value = "CreationUser"
          Range("AH1").Value = "CommentText"
          Range("AI1").Value = "FirstName"
          Range("AJ1").Value = "MiddleName"
          Range("AK1").Value = "LastName"
          Range("AL1").Value = "AddressId"
          Range("AM1").Value = "AddressLine1"
          Range("AN1").Value = "AddressLine2"
          Range("AO1").Value = "AddressLine3"
          Range("AP1").Value = "City"
          Range("AQ1").Value = "State"
          Range("AR1").Value = "PostalArea"
          Range("AS1").Value = "Country"
          Range("AT1").Value = "SecondaryFirstName"
          Range("AU1").Value = "SecondaryMiddleName"
          Range("AV1").Value = "SecondaryLastName"
          Range("AW1").Value = "SecondaryAddressId"
          Range("AX1").Value = "SecondaryAddressLine1"
          Range("AY1").Value = "SecondaryAddressLine2"
          Range("AZ1").Value = "SecondaryAddressLine3"
          Range("BA1").Value = "SecondaryCity"
          Range("BB1").Value = "SecondaryState"
          Range("BC1").Value = "SecondaryPostalArea"
          Range("BD1").Value = "SecondaryCountry"
          Range("BE1").Value = "EventVenue"
          Range("BG1").Value = "EventName"
          Range("BG1").Value = "EventDate"
          Range("BH1").Value = "AgreementVenueOrganizer"
          Range("BI1").Value = "AgreementReason"
    
        End If
    
        If InStr(myFile, "Consent11_MSD") > 0 Then
    
        'Add Column Headings
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "ConsentId"
          Range("J1").Value = "CompanyId"
          Range("K1").Value = "ConsentType"
          Range("L1").Value = "ConsentIndicator"
          Range("M1").Value = "CustomerId"
          Range("N1").Value = "ExpensePurposeCode"
          Range("O1").Value = "EffectiveDate"
          Range("P1").Value = "EndDate"
          Range("Q1").Value = "ConsentDate"
          Range("R1").Value = "CommentText"
          Range("S1").Value = "AgreementId"
          Range("T1").Value = "CustomerExpenseId"
          Range("U1").Value = "MeetingId"
          Range("V1").Value = "DataSourceId"
          Range("W1").Value = "ClientField1"
          Range("X1").Value = "ClientField2"
          Range("Y1").Value = "ClientField3"
          Range("Z1").Value = "ClientField4"
          Range("AA1").Value = "ClientField5"
          Range("AB1").Value = "N/A"
    
        End If
    
        'Save and Close Workbook
          wb.Close SaveChanges:=True
    
        'Ensure Workbook has closed before moving on to next line of code
          DoEvents
    
        'Get next file name
          myFile = Dir
      Loop
    
    'Message Box when tasks are completed
      MsgBox "Task Complete!"
    
    ResetSettings:
      'Reset Macro Optimization Settings
        Application.EnableEvents = True
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    
    End Sub
    

    STRIPPED DOWN CODE FOR TEST

    Sub LoopAllExcelFilesInFolder()
    'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
    'SOURCE: www.TheSpreadsheetGuru.com
    
    Dim wb As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim FldrPicker As FileDialog
    
    'Optimize Macro Speed
      Application.ScreenUpdating = False
      Application.EnableEvents = False
      Application.Calculation = xlCalculationManual
    
    'Retrieve Target Folder Path From User
      Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    
        With FldrPicker
          .Title = "Select A Target Folder"
          .AllowMultiSelect = False
            If .Show <> -1 Then GoTo NextCode
            myPath = .SelectedItems(1) & "\"
        End With
    
    'In Case of Cancel
    NextCode:
      myPath = myPath
      If myPath = "" Then GoTo ResetSettings
    
    'Target File Extension (must include wildcard "*")
      myExtension = "*.xls*"
    
    'Target Path with Ending Extention
      myFile = Dir(myPath & myExtension)
    
    'Loop through each Excel file in folder
      Do While myFile <> ""
        'Set variable equal to opened workbook
          Set wb = Workbooks.Open(Filename:=myPath & myFile)
    
        'Ensure Workbook has opened before moving on to next line of code
          DoEvents
    
          myFile = "20170614Agreement01_MSD.xls"
    
                If getTextBtwnNumbers(myFile) = "Agreement" Then
    
        'Add Text
          wb.Worksheets(1).Range("F1").Value = "Error code"
          Range("G1").Value = "Error description"
          Range("H1").Value = "ActionCode"
          Range("I1").Value = "ProfessionalId"
          Range("J1").Value = "StatusCode"
          Range("K1").Value = "ProfessionalTypeCode"
          Range("L1").Value = "StatusDate"
          Range("M1").Value = "Qualification"
          'etc etc etc
    
        End If
    
        'Save and Close Workbook
          wb.Close SaveChanges:=True
    
        'Ensure Workbook has closed before moving on to next line of code
          DoEvents
    
        'Get next file name
          myFile = Dir
      Loop
    
    'Message Box when tasks are completed
      MsgBox "Task Complete!"
    
    ResetSettings:
      'Reset Macro Optimization Settings
        Application.EnableEvents = True
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    
    End Sub
    
    Private Function getTextBtwnNumbers(s As String) As String
        Dim pos1 As Long, pos2 As Long
        Dim i As Long, j As Long
    
        For i = 1 To Len(s)
            If pos1 = 0 Then
                Select Case Asc(Mid(s, i, 1))
                Case 65 To 90, 97 To 122
                    pos1 = i
                End Select
            Else
                For j = pos1 To Len(s)
                    Select Case Asc(Mid(s, j, 1))
                    Case 65 To 90, 97 To 122
                    Case Else
                        pos2 = j ' - 1
                        Exit For
                    End Select
                Next j
            End If
    
            If pos1 <> 0 And pos2 <> 0 Then Exit For
        Next i
    
        If pos1 <> 0 And pos2 <> 0 Then
            getTextBtwnNumbers = Trim(Mid(s, pos1, pos2 - pos1))
        Else
            getTextBtwnNumbers = "Invalid Text Format"
        End If
    End Function
    
    • Philip Connell
      Philip Connell almost 7 years
      yep I could definitely of done with minimal in mind here. Thank you for the tip :-)
  • Philip Connell
    Philip Connell almost 7 years
    Hi Siddhart. Thank you for taking the time to respond it is greatly appreciated. I like your code example as a solution but unfortunately the numbers at the front and back do not remain the same everytime. 20170614 is a date and this will change. But maybe we can work this another way, what if I had code that deleted characters in the file name. I could then just tell the looping code hey look for "Agreement". Would this approach work???
  • Siddharth Rout
    Siddharth Rout almost 7 years
    It doesn't matter what the number is :) There has to be a number.. whatever that may be. It can be 111AAA222 or 20170614Agreement01_MSD or 123345678SID43211456 or anything. The format has to be NTN (NumberTextNumber)
  • Philip Connell
    Philip Connell almost 7 years
    ah ok: I i will give that a try. I added some code there to begin on the other solution in your answer. Please ignore until I try your original approach :-) Oh and thank you for the support :-) much appreciated :-)
  • Siddharth Rout
    Siddharth Rout almost 7 years
    I already rejected your edit :) Please do not edit my answer to post clarification. Feel free to edit your question.
  • Philip Connell
    Philip Connell almost 7 years
    Sorry about that. I was unaware of that editing rule. I apologies for that. I have tried the approach you have kindly offered and the code now just loops through adding the Agreement headings to all files. Have I done something wrong?
  • Siddharth Rout
    Siddharth Rout almost 7 years
    If getTextBtwnNumbers(flName) = "Agreement" Then You need to change the word "Agreement" in that code with the relevant text which you want to check :)
  • Siddharth Rout
    Siddharth Rout almost 7 years
    I think you need to use it like this If getTextBtwnNumbers(myFile) = "Agreement" Then
  • Philip Connell
    Philip Connell almost 7 years
    Hi. Yes I made those changes but the code keeps going to the other files and adding the Agreement Text. It does what it is supposed to do with the Agreement file and then It keeps going
  • Siddharth Rout
    Siddharth Rout almost 7 years
    Can you update your question with the code that you are using?
  • Philip Connell
    Philip Connell almost 7 years
    Hi I just added the code that I am using now. It is a stripped down version but this is putting all the Text values into all the files present in the folder. Thank you again for the help. CODE piece is STRIP DOWN CODE FOR TEST
  • Siddharth Rout
    Siddharth Rout almost 7 years
    myFile = "20170614Agreement01_MSD.xls" You have hardcoded the file name and hence If getTextBtwnNumbers(myFile) = "Agreement" Then will always be true :) Remove that line. The myFile = Dir(myPath & myExtension) is already taking care of the filename.
  • Philip Connell
    Philip Connell almost 7 years
    BOO YAAAHH! Victory!! VICTORY lap STACK OVERFLOW VICTORY LAP :-) :-) thank you so much for all you help Siddharth. MUCH respect from Dublin that has worked like a Charm :-) THANK YOU
  • Siddharth Rout
    Siddharth Rout almost 7 years
    I realised that there is a much better way. I have updated the above post :
  • Philip Connell
    Philip Connell almost 7 years
    There is only one word for that, and that is 'SLICK' :-) That is some SLICK VBA right there :-) Thank you Siddharth much appreciated :-)