+ Reply to Thread
Results 1 to 19 of 19

Compare files in folder with comments in sheet, rename files based on conditions

Hybrid View

  1. #1
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Compare files in folder with comments in sheet, rename files based on conditions

    I have a folder with txt files and in a sheet I have comments from A1 going down to A...
    I would like to compare the txt filenames with the values in the sheet and rename the files per example below.


    In the folder, the files are named in various ways, as an example:

    Mark; repopulate - export.txt
    [came to early] Nick .txt
    John - late for work.txt
    etc



    In a sheet, starting at A1 and going down (A2,A3 A4 etc) I have a list of comments. The important thing about the comments is that
    they have a number in front before the comment begins and the number is separated by a space before the actual comment. For example,

    1 Mark, repopulate
    20 John Late
    100 Nick to early
    etc


    I would like to compare the txt filenames with the comments in the sheet from A1 going down to A..., and when there is a match of most words, add the number in front of the filename of the txt.
    So with the above example,

    Mark; repopulate - export.txt to be renamed to 1 Mark; repopulate - export.txt
    [came to early] Nick.txt to be renamed to 100 [came to early] Nick.txt
    John - late for work.txt to be renamed 20 John - late for work.txt

    I hope the above makes sense.

    Any help is greatly appreciated. Thank you.

  2. #2
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    2013 | 2019 | 2021
    Posts
    14,958

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    Hi sans

    Not the most elegant....
    Option Explicit
    
    Sub Rename_Files()
    Dim Fso As Object, objFolder As Object, File As Object
    Dim Path As String, Name As String, Num As String, NewName As String
    Dim cell As Range, x As Long, Word
    Application.ScreenUpdating = False
    Path = ThisWorkbook.Path & "\Txt Folder\" 'change Txt Folder to name of folder housing txt files
    Set Fso = CreateObject("Scripting.filesystemobject")
    Set objFolder = Fso.GetFolder(Path)
    For Each File In objFolder.Files
        Name = Left(File.Name, (InStrRev(File.Name, ".", -1, vbTextCompare) - 1))
        With ActiveSheet
            For Each cell In .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
                Num = Left(cell, Application.Find(" ", cell))
                Word = Split(cell, " ")
                For x = 0 To UBound(Word)
                    If Name Like "*" & Word(x) & "*" Then
                        NewName = Num & Name
                        GoTo nxt
                    End If
                Next x
            Next cell
        End With
    nxt:
        File.Name = NewName & ".txt"
    Next File
    Application.ScreenUpdating = True
    End Sub
    Last edited by Sintek; 11-24-2018 at 06:06 AM.
    Good Luck...
    I don't presume to know what I am doing, however, just like you, I too started somewhere...
    One-day, One-problem at a time!!!
    If you feel I have helped, please click on the [★ Add Reputation] to left of post window...
    Also....Add a comment if you like!!!!
    And remember...Mark Thread as Solved...
    Excel Forum Rocks!!!

  3. #3
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    Thank you for the reply. How is the folder that contains the txt files selected? I can't figure it out. I get an error on line
    Set objFolder = Fso.GetFolder(Path)

  4. #4
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    2013 | 2019 | 2021
    Posts
    14,958

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    My setup for testing as follows:

    save workbook containing comments in ColA to desktop or any path
    save folder containg txt files to desktop or same path as workbook...

  5. #5
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    I'm sorry but I can't figure it out. Some more information regarding my original post.

    Let's assume I have a folder on the desktop and within that folder I have hundreds of txt files. For example:

    Mark; repopulate - export.txt
    [came to early] Nick .txt
    John - late for work.txt
    etc


    Also I have a blank workbook on the desktop, with only one sheet (Sheet1) and in Column A of the sheet I have the comments starting at A1 and going down. For example:

    1 Mark, repopulate (in A1)
    20 John Late (in A2)
    100 Nick to early (in A3)
    etc

    I would like to compare the filenames of the txt files and the comments in Column A - and when there is a match of most words, extract the number that appears in front of the comment and prefix it in front of the txt filename.
    So what I am looking for is renaming the txt files with a prefix.

    So with the above example,
    The file
    Mark; repopulate - export.txt
    will be renamed to
    1 Mark; repopulate - export.txt
    (the end result is that number 1 is prefixed to the filename of the txt)

    The file
    John - late for work.txt
    will be renamed
    20 John - late for work.txt
    (the end result is that number 20 is prefixed to the filename of the txt)

    The file
    [came to early] Nick.txt
    will be renamed to
    100 [came to early] Nick.txt
    (the end result is that number 100 is prefixed to the filename of the txt)
    Last edited by sans; 11-24-2018 at 07:43 AM.

  6. #6
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    2013 | 2019 | 2021
    Posts
    14,958

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    I'm sorry but I can't figure it out.
    Let's assume I have a folder on the desktop and within that folder I have hundreds of txt files.
    Also I have a blank workbook on the desktop, with only one sheet (Sheet1) and in Column A of the sheet I have the comments starting at A1 and going down.
    Exactly as above...put the code i supplied in this blank workbook...save it as macro enabled file...
    Run the code...
    Edit...
    Remember to change the red part of the code....to the name of your folder housing the txt files
    Path = ThisWorkbook.Path & "\Txt Folder\"
    Last edited by Sintek; 11-24-2018 at 08:01 AM.

  7. #7
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    I did a quick test and I get lots of duplicates which makes it very difficult to check the results.

    By duplicates, I mean that the number prefixed in a lot of the txt files is the same. For example, I get

    1 Mark, repopulate (in A1)
    1 John Late (in A2)
    100 Nick to early (in A3)
    etc


    The filename of each txt file is unique in the sense that when comparing it with Column A, there will be no "conflict" as to what number needs to be prefixed to the txt file, per the example above.


    Also, each number appears one time in the comments in Column A, so it is not possible to appear more than one time when its being prefixed to the txt file.


    I hope I am making sense, I'm trying to be clear in my explanation.

    Thank you.

  8. #8
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    2013 | 2019 | 2021
    Posts
    14,958

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    The code supplied - when run once....does what is required as per your initial request in Post1 & post5...
    Mark; repopulate - export.txt to be renamed to 1 Mark; repopulate - export.txt
    [came to early] Nick.txt to be renamed to 100 [came to early] Nick.txt
    John - late for work.txt to be renamed 20 John - late for work.txt
    If this is not what your requirement is then I suggest you post a workbook with the Col A comments and give examples of the txt filenames ...
    with a expected output...

    Perhaps someone can figure out what your requirement is...

  9. #9
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    I am uploading an example. Assume that you have the following txt files:

    Jame - performed very well - was on time.txt
    Jane ; Was Sick Today; Came Late.txt
    John ; was on time - he was not ok.txt
    Mark - Did not come to Work on time .txt
    Mark ; changed the time with another person.txt
    Mick ; was late for work - he performed well.txt

    The files will be renamed to:

    6 Jame - performed very well - was on time.txt
    3 Jane ; Was Sick Today; Came Late.txt
    1 John ; was on time - he was not ok.txt
    2 Mark - Did not come to Work on time .txt
    4 Mark ; changed the time with another person.txt
    5 Mick ; was late for work - he performed well.txt
    Comparing the txt filenames and the comments in Column A, which txt file refers to which cell in Column A, is based on matching the most words.
    Then extract the number that appears in front of the comment and prefix it in front of the txt filename. There are no repeating numbers in front of each comment in Column A, so similarly
    there should be no same number prefixed in front of multiple txt files.

    Thank you
    Attached Files Attached Files

  10. #10
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    2013 | 2019 | 2021
    Posts
    14,958

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    My apologies sans...offhand I can't think of any other way of doing this...Perhaps someone else can come up with an alternate solution...

    This works, however, I cannot guarantee that it would work on other scenarios...
    Option Explicit
    
    Sub Rename_Files()
    Dim Fso As Object, Numbers As Object, objFolder As Object, File As Object
    Dim Path As String, Name As String, Num As String, NewName As String
    Dim Word, cell As Range
    Application.ScreenUpdating = False
    Path = ThisWorkbook.Path & "\Txt Folder\"
    Set Fso = CreateObject("Scripting.filesystemobject")
    Set Numbers = CreateObject("System.Collections.ArrayList")
    Set objFolder = Fso.GetFolder(Path)
    For Each File In objFolder.Files
        Name = Left(File.Name, (InStrRev(File.Name, ".", -1, vbTextCompare) - 1))
        With ActiveSheet
            For Each cell In .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
                Word = Split(cell, " ")
                If Name Like "*" & Word(1) & "*" Then
                    Num = Left(cell, Application.Find(" ", cell))
                    If Not Numbers.contains(Num) Then Numbers.Add (Num) Else: GoTo nxt1
                    NewName = Num & Name
                    GoTo nxt2
                End If
    nxt1:
            Next cell
        End With
    nxt2:
        File.Name = NewName & ".txt"
    Next File
    Application.ScreenUpdating = True
    End Sub
    Untitled.png
    Last edited by Sintek; 11-26-2018 at 01:14 AM.

  11. #11
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    I tested it quickly but I get mixed results, especially when there are a lot of txt files compared to only a few.

    Just to mention in case the following points affect the results, the number of txt files is only sometimes exactly the same as the comments in Column A. Most times the txt files are less, for example,
    there might be 100 txt files but 200 comments.

    Also in the txt filenames and in the comments, there are mixed characters except the alphabetical ones (commas, exclamation marks,semicolons, dashes etc).

    I will test it more and will get back. Thank you for the reply.

  12. #12
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    sans,

    See if this works.
    Sub test()
        Dim myDir As String, fn As String, x
        With Application.FileDialog(msoFileDialogFolderPicker)
            If .Show Then myDir = .SelectedItems(1) & "\"
        End With
        If myDir = "" Then Exit Sub
        fn = Dir(myDir & "*.txt")
        Do While fn <> ""
            x = VLookLike(fn, Sheets(1).Cells(1).CurrentRegion.Columns(1))
            If x <> "" Then Name myDir & fn As myDir & Val(x) & " " & fn
             fn = Dir
        Loop
    End Sub
    
    Function VLookLike(txt As String, rng As Range) As String
        Dim i As Long, e, myName As String
        Dim a(), n As Long, x, temp, m As Object
        With CreateObject("VBScript.RegExp")
            .Global = True
            .Pattern = "^[A-Z][a-z]+"
            If .test(txt) Then
                myName = .Execute(txt)(0)
                For Each e In rng.Columns(1).Value
                    .Pattern = "\d+[; -]*" & myName & "[ ;-]*(.+)"
                    If .test(e) Then
                        n = n + 1
                        ReDim Preserve a(1 To 2, 1 To n)
                        a(1, n) = e: a(2, n) = 0
                        temp = .Execute(e)(0).submatches(0)
                        .Pattern = " *[;-]+ *"
                        temp = Replace(Application.Trim(.Replace(temp, " ")), " ", "|")
                        .Pattern = "\b(" & temp & ")\b"
                        For Each m In .Execute(txt)
                            a(2, n) = a(2, n) + Len(m)
                        Next
                    End If
                Next
            End If
        End With
        If n > 0 Then
            With Application
                x = Application.Max(.Index(a, 2, 0))
                If x > 0 Then VLookLike = a(1, .Match(x, .Index(a, 2, 0), 0))
            End With
        End If
    End Function

  13. #13
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    Thank you jindon for the reply. I tried it but I get no activity (or error). In my testing workbook, the data is in Sheet1, in column A1:A12.

    What am I doing wrong?

  14. #14
    Forum Guru Sintek's Avatar
    Join Date
    12-04-2015
    Location
    Cape Town
    MS-Off Ver
    2013 | 2019 | 2021
    Posts
    14,958

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    jindon's code ...For my scenario...works flawlessly...As always...

    Sorry I couldn't solve sans...So we all learn...tx for added rep +

  15. #15
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    Running on the test example is no problem and I get correct results. Running it on other files, I get no activity which is very strange.

  16. #16
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    Quote Originally Posted by sans View Post
    Running on the test example is no problem and I get correct results. Running it on other files, I get no activity which is very strange.
    Very strange.
    If it doesn't work, either your list/file names are different.
    See attached, it replicates what it should do in the worksheet.
    Attached Files Attached Files

  17. #17
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    I tested it on a sample of 100 txt files. For seven files, it didn't prefix the number which is no problem, for the rest of the 93 all were correct. I found what I was doing wrong, it was the formatting of the numbers in column A,
    because of the large number of files,to keep a right order, the formatting I have is

    001. File1.txt
    002. File2.txt
    003. File3.txt
    etc

    I changed the formatting in column A to

    1 File1.txt
    2 File2.txt
    3 File3.txt


    and it renamed the txt files without problem. Then I used a renaming utility to format the txt files back to 000 format so I can get them in ascending order, which again is no problem.

    It was my fault that I assumed it can be any number formatting as long as its separated by space. If its no problem to get a modification of your code for 000. formatting, it would be great.
    If not, again is not an issue. The code works perfect for what I want it to do.

    Thank you

  18. #18
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    Try change to
    Sub test()
        Dim myDir As String, fn As String, x
        With Application.FileDialog(msoFileDialogFolderPicker)
            If .Show Then myDir = .SelectedItems(1) & "\"
        End With
        If myDir = "" Then Exit Sub
        fn = Dir(myDir & "*.txt")
        Do While fn <> ""
            x = VLookLike(fn, Sheets(1).Cells(1).CurrentRegion.Columns(1))
            If x <> "" Then Name myDir & fn As myDir & x & " " & fn
             fn = Dir
        Loop
    End Sub
    
    Function VLookLike(txt As String, rng As Range) As String
        Dim i As Long, e, myName As String
        Dim a(), n As Long, x, temp, m As Object
        With CreateObject("VBScript.RegExp")
            .Global = True
            .Pattern = "^[A-Z][a-z]+"
            If .test(txt) Then
                myName = .Execute(txt)(0)
                For Each e In rng.Columns(1).Value
                    .Pattern = "(\d+)[; -]*" & myName & "[ ;-]*(.+)"
                    If .test(e) Then
                        n = n + 1
                        ReDim Preserve a(1 To 2, 1 To n)
                        a(1, n) = .Execute(e)(0).submatches(0): a(2, n) = 0
                        temp = .Execute(e)(0).submatches(1)
                        .Pattern = " *[;-]+ *"
                        temp = Replace(Application.Trim(.Replace(temp, " ")), " ", "|")
                        .Pattern = "\b(" & temp & ")\b"
                        For Each m In .Execute(txt)
                            a(2, n) = a(2, n) + Len(m)
                        Next
                    End If
                Next
            End If
        End With
        If n > 0 Then
            With Application
                x = Application.Max(.Index(a, 2, 0))
                If x > 0 Then VLookLike = a(1, .Match(x, .Index(a, 2, 0), 0))
            End With
        End If
    End Function

  19. #19
    Valued Forum Contributor sans's Avatar
    Join Date
    10-19-2011
    Location
    London
    MS-Off Ver
    Excel 2010
    Posts
    550

    Re: Compare files in folder with comments in sheet, rename files based on conditions

    That's perfect! Exactly what I needed. Thank you for the continuous help

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Rename .pdf files in a folder
    By vijanand1279 in forum Excel Programming / VBA / Macros
    Replies: 10
    Last Post: 11-11-2019, 01:11 AM
  2. Rename Sheet name for all the excel files within the folder
    By pitamine in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 06-06-2017, 02:27 PM
  3. Rename Sheet name for all the excel files within the folder
    By banglong in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 10-12-2014, 11:45 PM
  4. [SOLVED] Rename Files in A folder
    By pradeepjassal in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 09-12-2012, 10:36 AM
  5. rename all the files in a folder based the names given in column A
    By aravindhan_31 in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 09-19-2008, 05:30 AM
  6. [SOLVED] rename files in a folder
    By Varun Nair in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 07-18-2006, 08:25 AM
  7. [SOLVED] rename all files in a folder
    By DIBS in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 01-05-2006, 02:50 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1