Consulting

Results 1 to 7 of 7

Thread: Using VBA to Copy Multiple Workbook Filenames into their Workbooks

  1. #1

    Using VBA to Copy Multiple Workbook Filenames into their Workbooks

    Hi all,

    I am a school administrator and in charge of our data. One of the platforms we use outputs data by classes (one workbook per class). I have found a VBA code that combines these workbooks into one, but one of the pieces that is missing is the teacher's name. The teacher's name is listed in the filename of each workbook, and I'm trying to pull that over. Here is the code that I've been trying to use, which is populating #NAME? instead of the filename. Something is going wrong (I think) in this part of the code: .Range("K2:K17").Formula = "=Filename"

    Any help would be appreciated - today is my first day looking at VBA!

    Sub FilenameAlmost()
        Dim myPath As String, FilesInPath As String
        Dim MyFiles() As String, Fnum As Long
        Dim mybook As Workbook
        Dim CalcMode As Long
        Dim sh As Worksheet
        Dim ErrorYes As Boolean
    
    
        'Fill in the path\folder where the files are
        myPath = "C:\Users\rbrock\Desktop\Dreambox"
    
    
        'Add a slash at the end if the user forget it
        If Right(myPath, 1) <> "\" Then
            myPath = myPath & "\"
        End If
    
    
        'If there are no Excel files in the folder exit the sub
        FilesInPath = Dir(myPath & "*.csv*")
        If FilesInPath = "" Then
            MsgBox "No files found"
            Exit Sub
        End If
    
    
        'Fill the array(myFiles)with the list of Excel files in the folder
        Fnum = 0
        Do While FilesInPath <> ""
            Fnum = Fnum + 1
            ReDim Preserve MyFiles(1 To Fnum)
            MyFiles(Fnum) = FilesInPath
            FilesInPath = Dir()
        Loop
    
    
        'Change ScreenUpdating, Calculation and EnableEvents
        With Application
            CalcMode = .Calculation
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
        End With
    
    
        'Loop through all files in the array(myFiles)
        If Fnum > 0 Then
            For Fnum = LBound(MyFiles) To UBound(MyFiles)
                Set mybook = Nothing
                On Error Resume Next
                Set mybook = Workbooks.Open(myPath & MyFiles(Fnum))
                On Error GoTo 0
    
    
                If Not mybook Is Nothing Then
    
    
            'Change cell value(s) in one worksheet in mybook
                    On Error Resume Next
                    With mybook.Worksheets(1)
                        If .ProtectContents = False Then
                            .Range("K2:K17").Formula = "=Filename"
                        Else
                            ErrorYes = True
                        End If
                    End With
    
    
    
    
    
    
                    If Err.Number > 0 Then
                        ErrorYes = True
                        Err.Clear
                        'Close mybook without saving
                        mybook.Close savechanges:=False
                    Else
                        'Save and close mybook
                        mybook.Close savechanges:=True
                    End If
                    On Error GoTo 0
                Else
                    'Not possible to open the workbook
                    ErrorYes = True
                End If
    
    
            Next Fnum
        End If
    
    
        If ErrorYes = True Then
            MsgBox "There are problems in one or more files, possible problem:" _
                 & vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
        End If
    
    
        'Restore ScreenUpdating, Calculation and EnableEvents
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = CalcMode
        End With
    End Sub
    Last edited by SamT; 06-15-2016 at 06:57 PM. Reason: Added CODE Tags with # icon

  2. #2
    VBAX Expert
    Joined
    May 2016
    Posts
    604
    Location
    You need to change the line

    .Range("K2:K17").Formula = "=Filename"

    to

    [VBA]Range("K2:K17").Formula = "=cell(" & Chr(34) & "Filename" & Chr(34) & ")"[/VBA]

    Note Chr(34) is the " character which has to be added in the above method because otherwise VBA will recognise it as the end of a string.

    This will give you the path name and the filename, so you need to use the mid function to extract just the name.

  3. #3
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
               If Not mybook Is Nothing Then 
     FileName = mybook.Name
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

  4. #4
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,646
    Instead of this 'stolen' code (without any reference) 2 lines suffice

    Sub M_snb()
      createobject("wscript.shell").run "cmd copy C:\Users\rbrock\Desktop\Dreambox\*.csv C:\Users\rbrock\Desktop\all.csv"
      workbooks.open "C:\Users\rbrock\Desktop\all.csv"
    end sub

  5. #5
    Quote Originally Posted by offthelip View Post
    You need to change the line

    .Range("K2:K17").Formula = "=Filename"

    to

    [VBA]Range("K2:K17").Formula = "=cell(" & Chr(34) & "Filename" & Chr(34) & ")"[/VBA]

    Note Chr(34) is the " character which has to be added in the above method because otherwise VBA will recognise it as the end of a string.

    This will give you the path name and the filename, so you need to use the mid function to extract just the name.

    Thanks this worked perfectly! I've been playing around with the MID function and haven't quite gotten it to where I want it to be, especially since teacher's names vary in length. Here is the way that the filenames are saved:
    C:\Users\rbrock\Desktop\Dreambox\Martinez-Overview-20160516-20160614.csv

    In this case, Martinez is the teacher, but there also are teachers with longer/shorter names. My goal is to have something that pulls out only the teacher's name for a cell.

  6. #6
    VBAX Expert
    Joined
    May 2016
    Posts
    604
    Location
    you already have the path which you are searching so you can do this:

    [VBA]myPath = "C:\Users\rbrock\Desktop\Dreambox"
    lent+1 = Len(myPath)
    Range("K2:K17").Formula = "=mid(cell(" & Chr(34) & "Filename" & Chr(34) & ")," & lent & ",1000)"
    [/VBA]
    Do you need to remove the -Overview.... bit?
    If you do you need to find where that starts to determine the length of the string, if it always starts with "overview" you can do a search in vba using the "instr" function

  7. #7
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    If Not mybook Is Nothing Then 
        FileName = mybook.Name  'teachername-overview...
    TeacherName = Left(filename, InStr(fileName, "-") - 1). 'A Teacher Name like Smith-Carlton will fail
    TeacherName = Left(filename, InStr(fileName, "-Overview") - 1) 'Smith-Carlton will work
    End If
    I don't see where you are writing the Workbook Names to the worksheet.

    I have found a VBA code that combines these workbooks into one,
    I don't see that either.

    What I see is that
    One by one, you write all the file names to an array
    One by one you open all the files named in the array
    One by one you write formulas into K2 thru K12 in the files named in the array

    What am I missing?
    Last edited by SamT; 06-16-2016 at 08:19 PM.
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

Posting Permissions

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