+ Reply to Thread
Results 1 to 19 of 19

Loop through a dynamic range.

Hybrid View

Sluggoslabang Loop through a dynamic range. 09-03-2016, 08:34 AM
alansidman Re: Loop through a dynamic... 09-03-2016, 09:51 AM
Sluggoslabang Re: Loop through a dynamic... 09-03-2016, 01:11 PM
alansidman Re: Loop through a dynamic... 09-03-2016, 04:25 PM
6StringJazzer Re: Loop through a dynamic... 09-03-2016, 10:18 PM
Sluggoslabang Re: Loop through a dynamic... 09-04-2016, 05:58 AM
6StringJazzer Re: Loop through a dynamic... 09-04-2016, 03:12 PM
alansidman Re: Loop through a dynamic... 09-04-2016, 11:46 AM
Sluggoslabang Re: Loop through a dynamic... 09-05-2016, 06:37 AM
6StringJazzer Re: Loop through a dynamic... 09-05-2016, 08:14 AM
Sluggoslabang Re: Loop through a dynamic... 09-05-2016, 09:28 AM
xlnitwit Re: Loop through a dynamic... 09-05-2016, 10:09 AM
Sluggoslabang Re: Loop through a dynamic... 09-05-2016, 11:06 AM
xlnitwit Re: Loop through a dynamic... 09-05-2016, 11:14 AM
Sluggoslabang Re: Loop through a dynamic... 09-05-2016, 01:20 PM
xlnitwit Re: Loop through a dynamic... 09-06-2016, 09:24 AM
Sluggoslabang Re: Loop through a dynamic... 09-06-2016, 11:38 AM
xlnitwit Re: Loop through a dynamic... 09-06-2016, 11:55 AM
Sluggoslabang Re: Loop through a dynamic... 09-06-2016, 02:41 PM
  1. #1
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Loop through a dynamic range.

    Hello,
    I'm wondering if someone could help me with a loop.
    Now I'm hardcoding the ranges (marked with red) in a loop and it takes a long time to go through all rows.
    First range: ("A2:U2")
    Second : ("A3:U3")
    etc.
    It should loop Until every cell in range("A*:U*") IsEmpty.

    Here is the code I have so far:

                Do While Len(FileName) > 0
                    Set wbk = Workbooks.Open(Path & FileName, UpdateLinks:=0)
                    
                    'Extract workbook name to Column "X", (adjacent to its value from "R19" or "P19", in Column "W" (see below))
                    wbdest.Worksheets("Sheet1").Range("X" & Rows.count).End(xlUp).Offset(1) = wbk.Name
               
                        wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp).Offset(1).Formula = "=MID(RC[-1],FIND(""ABC"",RC[-1])+3,6)"
                       
                            If wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp) < 160813 Then
                           
                                wbk.Sheets(1).Range("B39:S39") = wbdest.Worksheets("Sheet1").Range("A2:U2").Value
                                wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("R19")
                            Else
                                wbk.Sheets(1).Range("B39:S39") = wbdest.Worksheets("Sheet1").Range("A2:U2").Value
                                wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("P19")
                            End If
                    
                    wbk.Close SaveChanges:=False
                    FileName = Dir
                Loop
        
            With Range("W2", Cells(Rows.count, "W").End(xlUp))
            'Chose what to delete before calc. average
                .Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
                
                .Cells(.Cells.count).Offset(1, 0) = "=Average(" & .Cells.Address & ")"
            End With
    
        'Copy last row from "W" to "V", adjacent to Range("A2:U2") etc. (Not sure this works).
        ActiveSheet.Range("V" & Rows.Count).End(xlUp).Offset(1) = ActiveSheet.Range("W" & Rows.Count).End(xlUp)
    Any help would be much appreciated

  2. #2
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 insider Version 2505 Win 11
    Posts
    24,754

    Re: Loop through a dynamic range.

    Add a variable to determine the last row, ie:

    Dim lr as long
    lr = range("A" & rows.count).end(xlup).row
    then substitute the variable lr for the last row, ie:

    Range("A2:U" & lr)
    Alan עַם יִשְׂרָאֵל חַי


    Change an Ugly Report with Power Query
    Database Normalization
    Complete Guide to Power Query
    Man's Mind Stretched to New Dimensions Never Returns to Its Original Form

  3. #3
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    Alan,
    Thanks a lot for answering my question.
    First I must tell you I'm a noob to VBA so please have patience with me.
    I put the variable one line above the "Do While Len(FileName)>0" loop and changed the red marked ranges with Range("A2:U" & lr).
    The code runs perfect the first range ("A2:U2") but then stops.
    Can you please tell me how to loop it down the ranges from ("A2:U2") to ("A*:U*") until next range (all cells in ("A*:U*")) is empty.
    I guess this must be a new loop "outside" my first loop? (Loop in loop)
    Thanks again

  4. #4
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 insider Version 2505 Win 11
    Posts
    24,754

    Re: Loop through a dynamic range.

    it would be very helpful in understanding what you are attempting to do if you post a sample worksheet and explain what you wish to happen versus trying to understand what you want in your code with the current explanation.

  5. #5
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,995

    Re: Loop through a dynamic range.

    I think this is what you mean:

    Start in row 2
    Do Until cells in columns A-U are blank
       Perform an action
       Go to next row
    Loop
    This code should do that but I haven't tested it. It's not practical to build a test file from scratch, plus this is only part of your code and I don't know what else you have. If you attach your file I would be happy to test it.

      
                 Dim Rg As Range 
                 Dim R As Long ' Row          
                 Do While Len(FileName) > 0
                    Set wbk = Workbooks.Open(Path & FileName, UpdateLinks:=0)
                    
                    'Extract workbook name to Column "X", (adjacent to its value from "R19" or "P19", in Column "W" (see below))
                    wbdest.Worksheets("Sheet1").Range("X" & Rows.count).End(xlUp).Offset(1) = wbk.Name
               
                        wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp).Offset(1).Formula = "=MID(RC[-1],FIND(""ABC"",RC[-1])+3,6)"
                       
                            R = 2
                            Set Rg = Range(Cells(R, "A"), Cells(R, "U"))
                            Do Until Join(Application.Index(Rg.Value, 1, 0)) = ""
                               If wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp) < 160813 Then
                           
                                   wbk.Sheets(1).Range("B39:S39") = wbdest.Worksheets("Sheet1").Rg.Value
                                   wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("R19")
                               Else
                                   wbk.Sheets(1).Range("B39:S39") = wbdest.Worksheets("Sheet1").Rg.Value
                                   wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("P19")
                               End If
                               R = R + 1
                               Set Rg = Range(Cells(R, "A"), Cells(R, "U"))
                           Loop
                    
                    wbk.Close SaveChanges:=False
                    FileName = Dir
                Loop
        
            With Range("W2", Cells(Rows.count, "W").End(xlUp))
            'Chose what to delete before calc. average
                .Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
                '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
                
                .Cells(.Cells.count).Offset(1, 0) = "=Average(" & .Cells.Address & ")"
            End With
    
        'Copy last row from "W" to "V", adjacent to Range("A2:U2") etc. (Not sure this works).
        ActiveSheet.Range("V" & Rows.Count).End(xlUp).Offset(1) = ActiveSheet.Range("W" & Rows.Count).End(xlUp)
    Jeff
    | | |·| |·| |·| |·| | |:| | |·| |·|
    Read the rules
    Use code tags to [code]enclose your code![/code]

  6. #6
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    Thanks a lot for your code Jeff, but,
    I get Run-time error '438':
    Object doesn't support this property or method, in line:
    wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Rg.Value

    Here comes the full code with an explanation:

    Sub AllinTest3Folder()
    Dim FileName As String, Path As String
    Dim wbk As Workbook, wbdest As Workbook
    Dim ws As Worksheet
    Dim lRow As Long
    Dim StartCell As Range
    
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
    
    Path = "C:\Station\Div\GTA\Test\Test3\"
    FileName = Dir(Path & "*.xlsm")
    
    Set wbdest = Workbooks.Open("C:\Station\Div\GTA\viktutv.xlsm")
    
    Set StartCell = Range("W2")
    Set ws = ActiveSheet
        lRow = ws.Cells(ws.Rows.count, StartCell.Column).End(xlUp).Row
        ws.Range(StartCell, ws.Cells(lRow, "Y")).ClearContents
    
            Do While Len(FileName) > 0
                Set wbk = Workbooks.Open(Path & FileName, UpdateLinks:=0)
                    
                    'Extract workbook name to Column "X", (adjacent to its value from "R19" or "P19", in Column "W" (see below))
                    wbdest.Worksheets("Sheet1").Range("X" & Rows.count).End(xlUp).Offset(1) = wbk.Name
               
                        'Extract 'date'-numbers from filename
                        wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp).Offset(1).Formula = "=MID(RC[-1],FIND(""ABC"",RC[-1])+3,6)"
                       
                            'If date is older than 160813, Then
                            If wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp) < 160813 Then
                           
                                wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Range("A2:U2").Value
                                wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("R19")
                            Else
                                wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Range("A2:U2").Value
                                wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("P19")
                            End If
                    
                wbk.Close SaveChanges:=False
                FileName = Dir
            Loop
        
    With Range("W2", Cells(Rows.count, "W").End(xlUp))
    'Chose what to delete before calc. average
        .Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
        .Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
        '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
        '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
        .Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
                
        .Cells(.Cells.count).Offset(1, 0) = "=Average(" & .Cells.Address & ")"
    End With
        
        'Copy last row from "W" to "V", adjacent to Range("A2:U2") etc.etc.
        ActiveSheet.Range("V" & Rows.count).End(xlUp).Offset(1) = ActiveSheet.Range("W" & Rows.count).End(xlUp)
        
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
    End With
    
    End Sub
    From workbook viktutv.xlsm, Sheet1, code copy first range ("A2:U2") to first workbook, Sheet1 Range("B39:V39") in "Test3" folder.
    Then code "copy" the value in cell "R19" or "P19", in that workbook.
    Copied value is "pasted" into workbook viktutv.xlsm, column "W".
    This is repeated for all workbooks in "Test3" folder and so far everything works fine.

    After all workbook's "R19 or P19" values are pasted, code calculates the average and paste result in column "V" adjacent to range in use, i.e. If it is first range ("A2:U2") then it paste the result in "V2", second range ("A3:U3") in "V3" etc. etc.
    First row in workbook "viktutv.xlsm" have headers in column A-Y.
    Second to n-th row have numbers in many cells but not all, in column A-U.
    After n-th row, comes a row with emty cells from column "A" to "U" and the loop shall stop.

    As it is now, I have to manually change from first range ("A2:V2") to second range ("A3:V3") etc etc (see highlighted code in red).

    I hope this clarify what I try to accomplish with the code.

    Thanks again

  7. #7
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,995

    Re: Loop through a dynamic range.

    Quote Originally Posted by Sluggoslabang View Post
    wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Rg.Value
    I think this should be
    wbk.Sheets(1).Range("B39:V39").Value = wbdest.Worksheets("Sheet1").Rg.Value
    I can't offer anything else unless you attach your file, as suggested very wisely by alansidman.

  8. #8
    Forum Moderator alansidman's Avatar
    Join Date
    02-02-2010
    Location
    Steamboat Springs, CO
    MS-Off Ver
    MS Office 365 insider Version 2505 Win 11
    Posts
    24,754

    Re: Loop through a dynamic range.

    Attach a sample workbook. Make sure there is just enough data to demonstrate your need. Include a BEFORE sheet and an AFTER sheet in the workbook if needed to show the process you're trying to complete or automate. Make sure your desired results are shown, mock them up manually if necessary.

    Remember to desensitize the data.

    Click on GO ADVANCED and then scroll down to Manage Attachments to open the upload window.

  9. #9
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    Jeff,
    Same error with that line.
    Now I have attached a workbook that should make it easier to understand what I try to accomplish.

    Thanks again both of you
    Attached Files Attached Files

  10. #10
    Administrator 6StringJazzer's Avatar
    Join Date
    01-27-2010
    Location
    Tysons Corner, VA, USA
    MS-Off Ver
    MS 365 Family 64-bit 2502
    Posts
    26,995

    Re: Loop through a dynamic range.

    That is not a macro-enabled workbook.

  11. #11
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    6StringJazzer,
    Hello and thanks for working with my problem.
    Yes, I know it's not macro-enabled. It's only for visualizing the problem.
    Because of confidentiality, I can't upload the real workbooks.
    Try this:
    Create four new workbooks in a folder. Use my filenames and add values in cell R19 or cell P19 (Sheet1), depending on date in filename.
    Change paths for folder and "viktutv.xlsm" in my code, to suit yours.
    Copy and paste my code into a new module, in "viktutv.xlsm".
    Run the code.
    Now you will see my code only do the first range (A2-U2).
    I want it to do all of them (down to row 14).
    Hope this is understandable.

  12. #12
    Forum Guru xlnitwit's Avatar
    Join Date
    06-27-2016
    Location
    London
    MS-Off Ver
    Windows: 2010; Mac: 16.13 (O365)
    Posts
    7,085

    Re: Loop through a dynamic range.

    Hi,

    Rg is a variable and therefore not a property of a worksheet. Either you must use:
    wbk.Sheets(1).Range("B39:V39").Value = Rg.Value
    or something akin to this
    wbk.Sheets(1).Range("B39:V39").Value = wbdest.Worksheets("Sheet1").Range(Rg.Address).Value
    However from my brief perusal of the code I am not certain that Rg is being set using the correct worksheet.
    Don
    Please remember to mark your thread 'Solved' when appropriate.

  13. #13
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    Hi xlnitwit,
    Thanks for help.
    I tried both and both do the copying inside wbk.
    How to make it copy from wbdest?

  14. #14
    Forum Guru xlnitwit's Avatar
    Join Date
    06-27-2016
    Location
    London
    MS-Off Ver
    Windows: 2010; Mac: 16.13 (O365)
    Posts
    7,085

    Re: Loop through a dynamic range.

    Both of the Rg assignments should be changed from
    Set Rg = Range(Cells(R, "A"), Cells(R, "U"))
    to read
    Set Rg = wbdest.Worksheets("Sheet1").Range(wbdest.Worksheets("Sheet1").Cells(R, "A"), wbdest.Worksheets("Sheet1").Cells(R, "U"))
    or more simply
    Set Rg = wbdest.Worksheets("Sheet1").Cells(R, "A").Resize(1, 21)

  15. #15
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    xlnitwit,
    Yes, we are getting closer,
    Code get the ranges (from viktutv.xlsm) as intended but it test it only on the first workbook.
    It should be the other way round.
    Code should use one range (from viktutv.xlsm) at a time, on every workbook in wbk and then calculate the average.
    So, before code starts with the second range it must calculate the average and put that number in column "V" adjacent to it's range.
    I am sorry for my english but I hope you can understand what I'm trying to do.
    Btw, the loop doesn't stop at first range with empty cells, so it can't continue with the rest.

  16. #16
    Forum Guru xlnitwit's Avatar
    Join Date
    06-27-2016
    Location
    London
    MS-Off Ver
    Windows: 2010; Mac: 16.13 (O365)
    Posts
    7,085

    Re: Loop through a dynamic range.

    I'm afraid I do not follow what you are saying. Can you please post the full code that you have now and state clearly what is happening, as well as what should be happening?

  17. #17
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    Hi xlnitwit,
    Ok, here is another explanation:
    In Workbook "viktutv.xls(m)", (as you can download from this thread) you find the "ranges" I am talking about.
    You find them in "viktutv.xls(m)", and they are:
    First range is: Column "A" Row 2 to Column "U" Row 2, ("A2:U2").
    Second range is: Column "A" Row 3 to Column "U" Row 3, ("A3:U3").
    Last range is: last row with numbers in any cell, in column "A" to "U".
    In this example, row 14 is the last row, but must be dynamic in the code.

    In my "Test3" folder, I have many workbooks (*.xlsm).

    My code paste first range ("A2:U2") from "viktutv.xlsm", in first workbook in folder "Test3", in cells ("B39:V39").
    Extracts filename from first workbook in folder "Test3", extracts date from that filename.
    Then copying Cell R19 or P19 in first workbook in folder "Test3", and paste that value in column "W" in "viktutv.xls(m)", adjacent to its filename in column "X".
    Then code loop and do exactly the same with second workbook in folder "Test3",
    and so on, until the last workbook in folder "Test3".
    After deleting the highest value in column "W" in "viktutv.xlsm", my code calculates the average (of those values) and copy that value to cell "V2", adjacent to its range ("A2:U2").

    So far my code is working good.

    Here comes my problem:
    (I think we need another loop here for the ranges)
    Now I want the code to change from first range in "viktutv.xls(m)", to second range in "viktutv.xls(m)", and start from beginning again with first workbook in folder "Test3" (see above), and so on until all workbooks in folder "Test3", are processed with the second range.
    After that, paste the new average, adjacent to its range ("A3:U3").

    And so on, until the last range in "viktutv.xls(m)" is processed on all workbooks in folder "Test3".

    I hope this made everything crystal clear (joking)

    Here is my original code:
    Sub AllinTest3Folder()
    'Sent to ExcelForum
    Dim FileName As String, Path As String
    Dim wbk As Workbook, wbdest As Workbook
    Dim ws As Worksheet
    Dim lRow As Long
    Dim StartCell As Range
    
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
    
    Path = "C:\Station\Div\GTA\Test\Test3\"
    FileName = Dir(Path & "*.xlsm")
    
    Set wbdest = Workbooks.Open("C:\Station\Div\GTA\viktutv.xlsm")
    
    Set StartCell = Range("W2")
    Set ws = ActiveSheet
        lRow = ws.Cells(ws.Rows.count, StartCell.Column).End(xlUp).Row
        ws.Range(StartCell, ws.Cells(lRow, "Y")).ClearContents
    
            Do While Len(FileName) > 0
                Set wbk = Workbooks.Open(Path & FileName, UpdateLinks:=0)
                    
                    'Extract workbook name to Column "X", (adjacent to its value from "R19" or "P19", in Column "W" (see below))
                    wbdest.Worksheets("Sheet1").Range("X" & Rows.count).End(xlUp).Offset(1) = wbk.Name
               
                        'Extract 'date'-numbers from filename
                        wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp).Offset(1).Formula = "=MID(RC[-1],FIND(""ABC"",RC[-1])+3,6)"
                       
                            'If date is older than 160813, Then
                            If wbdest.Worksheets("Sheet1").Range("Y" & Rows.count).End(xlUp) < 160813 Then
                           
                                wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Range("A2:U2").Value
                                wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("R19")
                            Else
                                wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Range("A2:U2").Value
                                wbdest.Worksheets("Sheet1").Range("W" & Rows.count).End(xlUp).Offset(1) = wbk.Sheets(1).Range("P19")
                            End If
                    
                wbk.Close SaveChanges:=False
                FileName = Dir
            Loop
        
    With Range("W2", Cells(Rows.count, "W").End(xlUp))
    'Chose what to delete before calc. average
        .Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
        'Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
        '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
        '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
        'Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
                
        .Cells(.Cells.count).Offset(1, 0) = "=Average(" & .Cells.Address & ")"
    End With
        
        'Copy last row from "W" to "V", adjacent to Range("A2:U2") etc.etc.
        ActiveSheet.Range("V" & Rows.count).End(xlUp).Offset(1) = ActiveSheet.Range("W" & Rows.count).End(xlUp)
        
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
    End With
    
    End Sub
    Last edited by Sluggoslabang; 09-06-2016 at 11:41 AM.

  18. #18
    Forum Guru xlnitwit's Avatar
    Join Date
    06-27-2016
    Location
    London
    MS-Off Ver
    Windows: 2010; Mac: 16.13 (O365)
    Posts
    7,085

    Re: Loop through a dynamic range.

    Given that the original code does what is required, we can in theory simply add another loop like so

    Sub AllinTest3Folder()
    'Sent to ExcelForum
        Dim FileName As String, Path As String
        Dim wbk As Workbook, wbdest As Workbook
        Dim ws                    As Worksheet
        Dim lastRow               As Long
        Dim rowNum                As Long
        Dim StartCell             As Range
    
        With Application
            .ScreenUpdating = False
            .DisplayAlerts = False
            .EnableEvents = False
        End With
    
        Path = "C:\Station\Div\GTA\Test\Test3\"
    
        Set wbdest = Workbooks.Open("C:\Station\Div\GTA\viktutv.xlsm")
        Set ws = ActiveSheet
        lastRow = ws.Cells(ws.Rows.Count, "W").End(xlUp).Row
    
        ws.Range("W2:Y" & lastRow).ClearContents
        
        For rowNum = 2 To lastRow
            FileName = Dir(Path & "*.xlsm")
            Do While Len(FileName) > 0
                Set wbk = Workbooks.Open(Path & FileName, UpdateLinks:=0)
                'Extract workbook name to Column "X", (adjacent to its value from "R19" or "P19", in Column "W" (see below))
                wbdest.Worksheets("Sheet1").Range("X" & Rows.Count).End(xlUp).offset(1) = wbk.Name
    
                'Extract 'date'-numbers from filename
                wbdest.Worksheets("Sheet1").Range("Y" & Rows.Count).End(xlUp).offset(1).Formula = "=MID(RC[-1],FIND(""ABC"",RC[-1])+3,6)"
    
                'If date is older than 160813, Then
                If wbdest.Worksheets("Sheet1").Range("Y" & Rows.Count).End(xlUp) < 160813 Then
    
                    wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Cells(rowNum, "A").Resize(1, 21).Value
                    wbdest.Worksheets("Sheet1").Range("W" & Rows.Count).End(xlUp).offset(1) = wbk.Sheets(1).Range("R19")
                Else
                    wbk.Sheets(1).Range("B39:V39") = wbdest.Worksheets("Sheet1").Cells(rowNum, "A").Resize(1, 21).Value
                    wbdest.Worksheets("Sheet1").Range("W" & Rows.Count).End(xlUp).offset(1) = wbk.Sheets(1).Range("P19")
                End If
    
                wbk.Close SaveChanges:=False
                FileName = Dir
            Loop
        Next rowNum
        
        With Range("W2", Cells(Rows.Count, "W").End(xlUp))
            'Chose what to delete before calc. average
            .Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
            'Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
            '.Cells.Find(Application.Max(.Cells), lookat:=xlWhole).ClearContents
            '.Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
            'Cells.Find(Application.Min(.Cells), lookat:=xlWhole).ClearContents
    
            .Cells(.Cells.Count).offset(1, 0) = "=Average(" & .Cells.address & ")"
        End With
    
        'Copy last row from "W" to "V", adjacent to Range("A2:U2") etc.etc.
        ActiveSheet.Range("V" & Rows.Count).End(xlUp).offset(1) = ActiveSheet.Range("W" & Rows.Count).End(xlUp)
    
        With Application
            .ScreenUpdating = True
            .DisplayAlerts = True
            .EnableEvents = True
        End With
    
    End Sub
    This is extremely inefficient since you are opening and closing workbooks repeatedly but I fear I do not currently have sufficient time to refactor the code.

  19. #19
    Registered User
    Join Date
    08-10-2016
    Location
    Stockholm, Sweden
    MS-Off Ver
    Excel 2016
    Posts
    30

    Re: Loop through a dynamic range.

    WOW!!!
    You are an absolut genius.
    After a couple of modifications it works like a charm.
    A simple thanks is not enough, but what can I say!
    I agree, code is extremely inefficient. It takes a long time to process all workbooks but what to do.
    THANK YOU!!!

+ 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. [SOLVED] Dynamic range in a loop
    By trailonu in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 04-30-2015, 07:22 PM
  2. [SOLVED] Merge Cells in Dynamic Range using For loop
    By crazymazy in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 08-01-2013, 11:33 AM
  3. VBA Plot Multiple Charts Using Loop Through Dynamic Range
    By sanjeevpandey in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 01-30-2013, 07:38 AM
  4. [SOLVED] Multiple condtion For loop, dynamic named range
    By emburl in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 12-04-2012, 09:59 PM
  5. Replies: 12
    Last Post: 09-21-2012, 12:22 PM
  6. Loop with dynamic range
    By mthomas in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 12-22-2011, 10:35 PM
  7. Loop through range names for location of dynamic paste
    By AlvaroSiza in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 08-17-2011, 11:01 AM

Tags for this Thread

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