+ Reply to Thread
Results 1 to 11 of 11

Cycling through files in a folder

Hybrid View

  1. #1
    Registered User
    Join Date
    09-21-2009
    Location
    Nottingham, UK
    MS-Off Ver
    Excel 2003
    Posts
    5

    Cycling through files in a folder

    Hi all,

    I'm a novice with VB, so go easy on me. I'm trying to write a macro to copy the same couple of cells from hundreds of excel files and paste them into one summary file. What I've written so far is:

    Sub Test()
    Dim x As Integer
    Dim y As Integer
    Dim name As String
    Dim name2 As String
    Dim wb As String
    Dim wb2 As String
    x = 3
    y = 10
    name = "WM19-1-014_00"
    name2 = "WM19-1-014_0"
    Do While (x < 10)
    wb = "name" & "x" & ".xls"
    Workbooks("wb").Activate
    Range("A3:B3").Copy
    Workbooks("data").Worksheets("Sheet1").Activate
    Cells(A, "2*x").Paste
    x = x + 1
    Loop
    Do While (y < 63)
    wb2 = "name2" & "y" & ".xls"
    Workbooks("wb2").Activate
    Range("A3:B3").Copy
    Workbooks("data").Worksheets("Sheet1").Activate
    Cells(A, "2*y").Paste
    y = y + 1
    Loop
    End Sub
    Forgive the clumsy break down of the files; they range from 001 to 063, and since I don't know how to set x as a three digit number I decided to have a section for 1-9 and a second section (with the same code) for 10-63.

    The problem I think I'm having is in referencing the workbook (the debugger always stops on the worksheets(wb).Activate line). Ideally I'd like the macro to open the files itself, but given that I can't even make it work when they're open I think I should start small. The issue, I believe, is that I'm not referencing the file correctly, since I'm trying to use the 'name + x' format to cycle through the files, and either I'm doing it wrong or this sort of variable referencing isn't suitable for the function. I've tried all manner of different tactics to get the activate workbook function liking my workbook name, but have had no luck.

    Any help would be hugely appreciated, and once again, forgive my unsubtle coding.

    Kate
    Last edited by KateMolloy; 09-28-2009 at 08:55 AM.

  2. #2
    Forum Expert sweep's Avatar
    Join Date
    04-03-2007
    Location
    Great Sankey, Warrington, UK
    MS-Off Ver
    2003 / 2007 / 2010 / 2016 / 365
    Posts
    3,454

    Re: Cycling through files in a folder

    Hi,

    I think your error may be here

    wb = "name" & "x" & ".xls"
    this will set wb to namex.xls

    try

    wb = "name" & x & ".xls"
    and

    wb2 = "name2" & y & ".xls"
    Rule 1: Never merge cells
    Rule 2: See rule 1

    "Tomorrow I'm going to be famous. All I need is a tennis racket and a hat".

  3. #3
    Registered User
    Join Date
    09-21-2009
    Location
    Nottingham, UK
    MS-Off Ver
    Excel 2003
    Posts
    5

    Re: Cycling through files in a folder

    Hi Dave,

    Thanks for your help. You're right, I did need to delete the "s around the x and y (I'd thought of that and decided not to for some reason!), but unfortunately I'm still getting the same error when running. In case it helps, the error is:

    Runtime error 9. Subscript out of range.

    Kate

  4. #4
    Forum Expert sweep's Avatar
    Join Date
    04-03-2007
    Location
    Great Sankey, Warrington, UK
    MS-Off Ver
    2003 / 2007 / 2010 / 2016 / 365
    Posts
    3,454

    Re: Cycling through files in a folder

    There's a couple of places that you have variables in quotes, which will result in the code not working.

    There's a ready made macro here which you may find useful

  5. #5
    Registered User
    Join Date
    09-21-2009
    Location
    Nottingham, UK
    MS-Off Ver
    Excel 2003
    Posts
    5

    Re: Cycling through files in a folder

    Hi again,

    Thanks for the link, Dave, I've used the Macro you suggested and this has solved the problem I was having before. Unfortunately I've come across a new problem!

    I'm trying to do a basic copy and paste from one workbook to another. At the moment I have the sheets worked out (I think) but there's a problem with the pasting. The code I have in place at the moment (with a bit of extra around the edges) is:

     Do While strExtension <> ""
                Set wbOpen = Workbooks.Open(strPath & strExtension)
                With wbOpen
                    .Sheets("Sheet3").Select
                    Range("A3:B3").Copy
                    .Close SaveChanges:=False
                End With
                With wbNew
                    Cells(1, 1).Select
                    ActiveCell.SpecialCells(xlLastCell).Offset(1, 1).Select
                    ActiveSheet.Paste
                End With
                strExtension = Dir
            Loop
    The problem is that Excel doesn't like the ActiveSheet.Paste command for some reason! I've done the copy and paste manually while recording a Macro, and this is what it came up with, but when it's run on its own I get the error 'Object doesn't support this property or method'.

    I've tried loads of other paste options, including Selection.Paste and changing the Cell line above to .paste instead of .select (but I don't think the cells command works with paste), and changing the cells command to a range command, but this throws up yet more problems.

    I've simplified the macro to the real basics: I select the cells in the other workbook, then select the book I want to paste into and have the macro:

    Cells(1, 1).Select
                    ActiveCell.SpecialCells(xlLastCell).Select
                    Selection.Paste
    And while this is basically exactly what's recorded when I do it manually and record, when I run it as a macro I get the same problems.

    I've tried other methods of selecting the cell I need to paste into, such as columncount etc, but have had no luck either.

    I can't believe I'm having this much trouble with such a simple thing, so any help would be really appreciated!

    Thanks again,

    Kate

  6. #6
    Forum Expert sweep's Avatar
    Join Date
    04-03-2007
    Location
    Great Sankey, Warrington, UK
    MS-Off Ver
    2003 / 2007 / 2010 / 2016 / 365
    Posts
    3,454

    Re: Cycling through files in a folder

    Try activating a worksheet in wbNew by replacing this:

    With wbNew
    Cells(1, 1).Select
    with this:

    With wbNew
    Sheets(1).activate
    Cells(1, 1).Select
    I've used sheet 1 for an example.

  7. #7
    Registered User
    Join Date
    09-21-2009
    Location
    Nottingham, UK
    MS-Off Ver
    Excel 2003
    Posts
    5

    Re: Cycling through files in a folder

    Hi again Dave,

    Unfortunately that's one of the things I've tried. In fact I've still got it in in the mini macro I'm using to tease the problem out, but it hasn't helped. Should have posted it in the code, really, sorry about that.

    Just to check the line I have works, it's:

    Workbooks("data.xls").Worksheets("Sheet1").Activate

    Kate

  8. #8
    Forum Expert jaslake's Avatar
    Join Date
    02-21-2009
    Location
    Atwood Lake in Mid NE Ohio...look it up.
    MS-Off Ver
    Excel 2010 2019
    Posts
    12,749

    Re: Cycling through files in a folder

    This may help (or not); tryu replacing this code
    Selection.Paste
    with
    Selection.PasteSpecial
    Hope this helps.
    J
    John

    If you have issues with Code I've provided, I appreciate your feedback.

    In the event Code provided resolves your issue, please mark your Thread as SOLVED.

    If you're satisfied by any members response to your issue please use the star icon at the lower left of their post.

  9. #9
    Forum Expert
    Join Date
    01-03-2006
    Location
    Waikato, New Zealand
    MS-Off Ver
    2010 @ work & 2007 @ home
    Posts
    2,243

    Re: Cycling through files in a folder

    hi Kate,

    This may need some fine tuning but hopefully it will do what is needed once the changes are made - my idea of not using copy & paste removes the need to flick between files, removes the risk of something else being mistakenly put on the clipboard or the clipboard being cleared while the macro is running (it may be faster too but I'm not sure). I've included the LastCell Function, rather than coding it into the same macro, as you may find it useful for other code development too.

    Kate/Dave, some of your code in posts 5 & 6 respectively seems to be missing the dot prefixes for the range or sheet within the With statements.

    - fingers crossed...
    Option Explicit
    
    Sub Test1()
    Dim strExtension As Variant 'change to what this is meant to be - I didn't know if it works as a string
    Dim strPath As String
    Dim wbOpen As Workbook
    Dim wbNew As Workbook
    Dim ConsolSht As Worksheet
    Dim FirstEmptyOnConsolSht As Range
    
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
    
    Set wbNew = ThisWorkbook 'change as needed
    Set ConsolSht = wbNew.Worksheets("sheet1") 'change as needed
            Do While strExtension <> ""
                Set FirstEmptyOnConsolSht = ConsolSht.Range("a" & LastCell(ConsolSht).Row + 1).Resize(1, 2)
                Set wbOpen = Workbooks.Open(strPath & strExtension)
                With wbOpen
                    FirstEmptyOnConsolSht.Value = .Sheets("Sheet3").Range("A3:B3").Value
                    .Close SaveChanges:=False
                End With
                Set FirstEmptyOnConsolSht = Nothing
                strExtension = Dir
            Loop
    
    Set ConsolSht = Nothing
    Set wbNew = Nothing
    Set wbOpen = Nothing
    
    With Application
        .ScreenUpdating = true
        .DisplayAlerts = true
        .EnableEvents = true
    End With
    End Sub
    
    Function LastCell(ws As Worksheet) As Range
    ' sourced from http://www.beyondtechnology.com/geeks012.shtml
    'to identify the lastcell on a worksheet (& not necessarily the active sheet)
        Dim LastRow As Long
        Dim LastCol As Long
        ' Error-handling is here in case there is not any
        ' data in the worksheet
        On Error Resume Next
        With ws
            ' Find the last real row
            LastRow = .Cells.Find(What:="*", _
                                SearchDirection:=xlPrevious, _
                                SearchOrder:=xlByRows).Row
            LastRow = Application.WorksheetFunction.Max(1, LastRow)
            ' Find the last real column
            LastCol = .Cells.Find(What:="*", _
                                SearchDirection:=xlPrevious, _
                                SearchOrder:=xlByColumns).Column
            LastCol = Application.WorksheetFunction.Max(1, LastCol)
        End With
        On Error GoTo 0
        ' Finally, initialize a Range object variable for
        ' the last populated row.
        Set LastCell = ws.Cells(LastRow, LastCol)
    End Function
    hth
    Rob
    Last edited by broro183; 09-26-2009 at 06:50 PM. Reason: fixed code tags
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

  10. #10
    Registered User
    Join Date
    09-21-2009
    Location
    Nottingham, UK
    MS-Off Ver
    Excel 2003
    Posts
    5

    Re: Cycling through files in a folder

    Thanks to you all! I copied the text I had in my macro into a new file this morning and for some reason it's now working! Must have been a bug somewhere, I have no idea what, but luckily it's ok now.

    Particular thanks to Rob for that last post; it does seem like a nicer way of doing things, and I may experiment with it once I've got the job done, just out of interest.

    Thanks again, I really appreciate people taking time out of their days to help novices like me.

    Kate

  11. #11
    Forum Expert
    Join Date
    01-03-2006
    Location
    Waikato, New Zealand
    MS-Off Ver
    2010 @ work & 2007 @ home
    Posts
    2,243

    Re: Cycling through files in a folder

    Thanks for the feedback & marking the thread as solved - I'm pleased we could help :-)

    Rob

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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