Complicated (I think) Macro

ExcelAmateur2014

New Member
Joined
Dec 17, 2014
Messages
32
Hi

I have looked through your forums before joining in hope that the answer as there but haven' found it.

Basically I want to run a macro or something similar that will bring back the information from a set data range of all spreadsheets in that folder. Basically I am having a form that will be completed by other people which is in a set template format. I want to have a macro that will drag through the data range from each form within the folder automatically.

For example
There are 3 forms completed in the folder. I want my central data base to bring through the data on each form from cell B2. And relay it into the central spreadsheet eg.

Master spreads sheet will look like this after the Macro has run

A1 = 4
B1 = 2
C1 = 3

This basically has dragged through the data from cell B2 in each of the following spreadsheets which are all saved in a central folder.

Spreadsheet 1 – Cell B2 = 4
Spreadsheet 2 – Cell B2 = 2
Spreadsheet 3 – Cell B2 = 3

If I was then to add another spreadsheet into the folder “spreadsheet 4” which has the value of 7 in cell B2, then I run the Macro again then this data will then be added to cell D1 accordingly of the master sheet. Spreadsheet 5 will then feed into cell E1, spreadsheet 6 will feed data in to cell F1 of the mastersheet and so on.

Obviously if the data was static and not being added to with new spreadsheets then I could do a Vlockup or similar, but I’m sure there is a way to do this where it just looks for all spreadsheets within a folder.

Hopefully someone can help me with this please.

Thanks in advance
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
HTH. Dave
Code:
Option Explicit
Sub FsoCycleThroughFiles()
Dim Foldername As String, Cnt As Integer
Dim Filename As Object, FSO As Object
On Error GoTo ErrorHandler
Foldername = "C:\testpf\"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set FSO = CreateObject("Scripting.FileSystemObject")
For Each Filename In FSO.getfolder(Foldername).Files
'**change file extension to suit
If Right(Filename.Name, 3) = "xls" Then
Workbooks.Open (Filename)
Cnt = Cnt + 1
ThisWorkbook.Sheets("Sheet1").Cells(Cnt, 1) = _
  ActiveWorkbook.Sheets("Sheet1").Range("B" & 1).Value
ActiveWorkbook.Close savechanges:=False
End If
Next Filename
Set FSO = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Done"
Exit Sub

ErrorHandler:
MsgBox "An error occurred"
End Sub
 
Upvote 0
Thanks

sorry I am really amateur at this. I only know how to record macro not write VB. can you please give me a step guide as to how I incorporate your code into excel (2010) sorry for being a pain but really appreciate your help.

I presume I would need to change the following
Foldername = "C:\testpf\ - to the name of the folder where all files saved?

If the master sheet is called "Tracker 2.5" what parts of the code would I need to change?
If the individual spreadsheets I'm looking to get data from are called "book1.xlsx" "Book2.xlsx" and so what if any do I need to change?

Thanks in advance
 
Upvote 0
Welcome to the board...

Had to post my code after NdNoviceHlp - spent 20 minutes writing it, so gotta post it - both sets of code will work though.


Code:
Public Sub Main()


    Dim vFolder As Variant
    Dim vFile As Variant
    Dim colFiles As Collection
    Dim wrkBk As Workbook
    Dim lcol As Long
    Dim rng As Range
    
    'Ask for the folder location.
    vFolder = GetFolder()
    
    
    If vFolder <> "" Then
    
        'Get all Excel files from within folder.
        Set colFiles = New Collection
        EnumerateFiles vFolder, "*.xls*", colFiles
        
        For Each vFile In colFiles
            
            'Open the workbook without updating links.
            Set wrkBk = Workbooks.Open(CStr(vFile), False)
            
            'This is the workbook that this code is in.
            With ThisWorkbook.Worksheets("Sheet1")
            
                'Figure out where the last column on row 2 is.
                On Error Resume Next
                lcol = .Rows(2).Find("*", , , , xlByRows, xlPrevious).Column
                On Error GoTo 0
                If lcol = 0 Then
                    lcol = 1
                Else
                    lcol = lcol + 1
                End If
                
                'Paste data from B2 into the last cell.
                .Cells(2, lcol) = wrkBk.Worksheets(1).Cells(2, 2)
            End With
            
            'Close the workbook without saving.
            wrkBk.Close False
        Next vFile
    End If


End Sub


'---------------------------------------------------------------------------------------
' Procedure : GetFolder
' Purpose   : Returns the file path of the selected folder.
' To Use    : vFolder = GetFolder()
'           : vFolder = GetFolder("S:\Bartrup-CookD\Customer Services Phone Reports")
'---------------------------------------------------------------------------------------
Function GetFolder(Optional startFolder As Variant = -1) As Variant
    Dim fldr As FileDialog
    Dim vItem As Variant
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        If startFolder = -1 Then
            .InitialFileName = Application.DefaultFilePath
        Else
            If Right(startFolder, 1) <> "\" Then
                .InitialFileName = startFolder & "\"
            Else
                .InitialFileName = startFolder
            End If
        End If
        If .Show <> -1 Then GoTo NextCode
        vItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = vItem
    Set fldr = Nothing
End Function


'----------------------------------------------------------------------------------
' Procedure : EnumerateFiles
' Purpose   : Places all file names with FileSpec extension into a collection.
' To Use    : EnumerateFiles "S:\Bartrup-CookD\Trackers", "*.xls", colFiles
'-----------------------------------------------------------------------------------
Sub EnumerateFiles(ByVal sDirectory As String, _
    ByVal sFileSpec As String, _
    ByRef cCollection As Collection)


    Dim sTemp As String
    
    If InStrRev(sDirectory, "\") <> Len(sDirectory) Then
        sDirectory = sDirectory & "\"
    End If
    
    sTemp = Dir$(sDirectory & sFileSpec)
    Do While Len(sTemp) > 0
        cCollection.Add sDirectory & sTemp
        sTemp = Dir$
    Loop
End Sub

For either set of code - easiest way is to record a macro, delete the code it generated and paste the new code in (Alt + F11 to view the code)

Edit - to paste to another sheet other than Sheet1 change this line of code:
With ThisWorkbook.Worksheets("Sheet1")

This will pick up all xls, xlsx, xlsm, xlsb - anything with an extension starting xls and allows you to choose a folder at runtime.
 
Last edited:
Upvote 0
Thanks

Really appreciate the time this has taken you.

I have just gone to record a macro and then copied your code in, assigned your macro to a button and it doesn't work

presumably there are areas which I need to change? Where are these?

The file path of the folder with all the spreadsheets in is "Z:\Graphite phase 2\Graphite 2.5 Test Folder"

are there any other areas i would need to personalize?
Thanks
 
Upvote 0
What parts not working?

I just tested it - assigned the button to run the 'Main' macro and it worked fine.

The only bit I'd change would be to change the line in Main from:
vFolder = GetFolder()

to

vFolder = GetFolder("Z:\Graphite phase 2\Graphite 2.5 Test Folder") just so it goes to the correct folder without having to navigate to it.
 
Upvote 0
Brilliant. Thank you, I have got it to work now which is fantastic.
Just wondering now if you can help me switch the direct ion of the cells.
What part of the formula tells it to relay the data horizontally rather than vertical.

Ie the 3 results that come back appear in column b,c and d, when I really want it to relay in columns a2,a3,a4

Also I tried to record a macro that Clears the data (ie select all the sheet and then deletes everything) and then merge that macro in with the one you have just helped with, however, it doesn’t appear to like it. Basically I just want it to clear all data first before starting to run the other part of the macro

Can I compensate you in anyway for your troubles here as you have all been so helpful?
 
Last edited:
Upvote 0
To change it to rows you need to change these lines:
Code:
lcol = .Rows(2).Find("*", , , , xlByRows, xlPrevious).Column
to
Code:
lcol = .Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row

And this:
Code:
.Cells(2, lcol) = wrkBk.Worksheets(1).Cells(2, 2)
to
Code:
.Cells(lcol, 1) = wrkBk.Worksheets(1).Cells(2, 2)

You can use .Cells([row number], [col number]) rather than .Range([Cell Address]) - much easier to work with in code.

If you want to clear the sheet before the macro runs add this to the macro just before the For Each vFile in ColFiles line:
Code:
ThisWorkbook.Worksheets("Sheet1").Cells.ClearContents

ClearContents clears the contents of cells rather than delete them - so it won't muck up any formula referencing the cells.

Just a thanks is compensation enough :)

Edit: You may want to change the lCol variable to lRow so it's as obvious as can be what the variable refers to.
 
Upvote 0
That's very kind thank you.

I’m quite enjoying learning and playing with the encoding.
Now I have a few other questions I’m afraid

1) How do I make the data start in Column A2 rather than A1?
2) What order does it decide to look at the files in the folder and drag the data through. Basically the files are called book1 through 4 at the moment but it drags the data through in the order 4,2,1,3 rather than 1,2,3,4? Is there a way to amend this?
3) Now this data at present drags through cell B1 from my data sheets in to column “A”. I am now wanting for it to drag through data for cell C1 also to sit in my “B” column. Do I simply add this code all over again and change the cell to C1 rather than B1?
 
Upvote 0

Forum statistics

Threads
1,214,639
Messages
6,120,679
Members
448,977
Latest member
dbonilla0331

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top