+ Reply to Thread
Results 1 to 35 of 35

VBA For loop

Hybrid View

  1. #1
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    VBA For loop

    I need a little help getting in the right direction and I should be fine from there.

    So the background here is i have a huge 10K line data file I need to search through and find up to three unique results given two conditions. the first condition has a possible of 93 outcomes and the second condition has a possible of 5 outcomes; for a total of about 10k random entries. I want to grow this function to fill lots of data but I keep getting random issues. consistently "error 1004".

    This 10k file is updated constantly and i need to create reports for every year in the future so you're help here is really appreciated.

    
    Private Sub CommandButton3_Click()
        Dim LastRow As String
        Dim z As Integer
        Dim CellOne As String
        Dim CellTwo As String
        Dim CellThree As String
        
        'get the row count for the loop
        Sheets("2015 DATA").Select
        LastRow = Cells(Rows.Count, "A").End(xlUp).Row
    
        'now we loop, match all countries and classes and output the factories
             CellOne = None
             CellTwo = None
             CellThree = None
        
            Sheets("2015 DATA").Select
            Range("A1").Select
            
        For z = 1 To LastRow
        If Worksheets("2015 DATA").Cells(z, 9).Value = "CO" And Worksheets("2015 DATA").Cells(z, 27).Value = "class 12" Then
        
        If CellOne = None Then CellOne = Worksheets("2015 DATA").Cells(z, 7).Value
        If CellTwo = None Then CellOne = Worksheets("2015 DATA").Cells(z, 7).Value
        If CellThree = None Then CellOne = Worksheets("2015 DATA").Cells(z, 7).Value
        
        End If
    
        Next z
        
          MsgBox (CellOne & CellTwo & CellThree)
    End Sub
    Last edited by iamGreenhorn; 07-17-2014 at 09:41 AM.

  2. #2
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    hi iamGreenhorn, welcome to ExcelForum

    Can you provide details on the code to do and, if possible, a sample file (5-10 rows of data will be enough). It would also be helpful to get the result from the sample data you expect to get.

  3. #3
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Im going through each row with the Z for loop
    for every row we test two columns for their values (column 9 & 27)
    If the values in 9 & 27 pass we write the value in column 7 row Z to a variable and then move on to the next row untill we finish all rows

  4. #4
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    I cant really provide the data but:

    Im just trying to get it to loop through every row and if the two conditions here are met:

    If Worksheets("2015 DATA").Cells(z, 9).Value = "CO" And Worksheets("2015 DATA").Cells(z, 27).Value = "class 12" Then

    i want to write it to a cell. I was using the three variables as a way to not grab the same result three times aka it gets reset before the loop is entered and finds three different results.

    Im trying to write these to a box at the end just to test functionality

  5. #5
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: VBA For loop

    Why not just use Autofilter?
    Entia non sunt multiplicanda sine necessitate

  6. #6
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Quote Originally Posted by shg View Post
    Why not just use Autofilter?
    Because i started vba last thursday :D

    Is there a was to autofilter just down to the results. Like the possible answers?

  7. #7
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: VBA For loop

    Filter column I for "CO" and column AA for "class 12"

    What you see are just the rows that meet both criteria.

  8. #8
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    That is fine but i have in the past used a formula that works, plus as i said there are a lot more results than i wanna deal with on a daily basis. I want to use VBA to remove the hassle and inaccuracy of that.

    =IFERROR(INDEX('PT OOT 2013'!$A$2:$C$158;SMALL(IF('PT OOT 2013'!$A$2:$C$158=CS$1;ROW('PT OOT 2013'!$A$2:$C$158)-ROW('PT OOT 2013'!$A$2)+1;ROW('PT OOT 2013'!$C$158)+1);ROW(EY31)-29);2);"-")

  9. #9
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: VBA For loop

    If autofiltering gives the result you want, you can to that with VBA if you wish -- a few thousand times faster than what you have.

  10. #10
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Even with autofilter it doesnt boil down the results. i could sill have 100 mixed up entries and i could make it pull the first three unique entries but i still have the same loop and issue. Unless theres a way to use autofilter to get the possible results... like the boxes you check when you manually filter.. Does that exist as a quick google doesnt reveal it


    Also efficiency isnt really relevant if it takes a few minutes i can live
    If its really slow i can autofilter then run the loop.

  11. #11
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: VBA For loop

    Sub IAmG()
        Worksheets("2015 DATA").Select
    
        With Range("A:AA")
            .Worksheet.AutoFilterMode = False
            .AutoFilter Field:=9, Criteria1:="CO"
            .AutoFilter Field:=27, Criteria1:="class 12"
        End With
    End Sub

  12. #12
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    option basing on your code:

    Option Explicit
    
    Sub test()
    
    Dim sh As Worksheet, lrow As Long, j As Long, result
    Dim arr27, arr9, arr7, i As Long, mystr As String
    
    If IsError(Evaluate("'2015 DATA'!A1")) Then
        MsgBox "Sheet " & Chr(34) & "2015 DATA" & Chr(34) & " is not found", vbCritical, "Error"
        Exit Sub
    Else
        Set sh = Sheets("2015 DATA")
    End If
    
    lrow = sh.Cells(Rows.Count, "a").End(xlUp).Row
    
    If lrow = 1 Then
        If sh.Cells(1, 9) = "CO" And sh.Cells(1, 27) = "class 12" Then
            Sheets.Add.Range("a1").Value = sh.Cells(1, 7).Value
            Exit Sub
        End If
    End If
    
    arr7 = sh.Range("g1:g" & lrow)
    arr9 = sh.Range("i1:i" & lrow)
    arr27 = sh.Range("aa1:aa" & lrow)
    
    ReDim result(1 To lrow, 1 To 1)
    
    For i = 1 To lrow
        If arr9(i, 1) = "CO" And arr27(i, 1) = "class 12" Then
            If InStr(mystr, " " & arr7(i, 1) & " ") = 0 Then
                mystr = mystr & " " & arr7(i, 1) & " "
                j = j + 1
                result(j, 1) = arr7(i, 1)
            End If
        End If
    Next
    
    Application.ScreenUpdating = 0
    Sheets.Add.Range("a1:a" & j) = result
    Application.ScreenUpdating = 1
    
    End Sub
    Last edited by watersev; 07-14-2014 at 03:30 PM.

  13. #13
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Watersev, very nice code. thoughtful error handles.. very nice.
    But when I use it I get "runtime error 1004, Application-defined or object-defined error"
    It makes a new sheet and throws that error.

    If i quote out "Sheets.Add.Range("a1:a" & j) = result" It doesn't error but it still creates a blank sheet.
    I added a msgbox at the end and tried to display different things to see if it otherwise worked, it does calculate lrow correctly.. And if i print mystr it gives me every unique value in a string. :thumbsup

    I am new to this and this environment, im sure im implementing it wrong or something..

    Also I could use a little help understanding whats going on here:
    If InStr(mystr, " " & arr7(i, 1) & " ") = 0 Then
    mystr = mystr & " " & arr7(i, 1) & " "
    j = j + 1
    result(j, 1) = arr7(i, 1)
    Last edited by iamGreenhorn; 07-15-2014 at 04:56 AM.

  14. #14
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    hi there, updated code

    Option Explicit
    
    Sub test()
    
    Dim sh As Worksheet, lrow As Long, j As Long, result
    Dim arr27, arr9, arr7, i As Long, mystr As String
    
    If IsError(Evaluate("'2015 DATA'!A1")) Then
        MsgBox "Sheet " & Chr(34) & "2015 DATA" & Chr(34) & " is not found", vbCritical, "Error"
        Exit Sub
    Else
        Set sh = Sheets("2015 DATA")
    End If
    
    lrow = sh.Cells(Rows.Count, "a").End(xlUp).Row
    
    If lrow = 1 Then
        If sh.Cells(1, 9) = "CO" And sh.Cells(1, 27) = "class 12" Then
            Sheets.Add.Range("a1").Value = sh.Cells(1, 7).Value
            Exit Sub
        End If
    End If
    
    arr7 = sh.Range("g1:g" & lrow)
    arr9 = sh.Range("i1:i" & lrow)
    arr27 = sh.Range("aa1:aa" & lrow)
    
    ReDim result(1 To lrow, 1 To 1)
    
    For i = 1 To lrow
        If arr9(i, 1) = "CO" And arr27(i, 1) = "class 12" Then
            If InStr(mystr, " " & arr7(i, 1) & " ") = 0 Then
                mystr = mystr & " " & arr7(i, 1) & " "
                j = j + 1
                result(j, 1) = arr7(i, 1)
            End If
        End If
    Next
    
    If j > 0 Then
        Application.ScreenUpdating = 0
        Sheets.Add.Range("a1:a" & j) = result
        Application.ScreenUpdating = 1
    End If
    
    End Sub
    The Instr part helps to identify unique items in 7th column

  15. #15
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop



    Thank you so much, hopefully i can apply this properly

  16. #16
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    The code was written blindly without seeing the actual data. Sometimes that results in some changes being required to the code

  17. #17
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Watersev,

    I just about finished this project but when i run your block of code inside another for loop to fill an array it doesnt work.
    It keeps filling the results from the first search. It seems if i change j it works but i can have that many variables.. If i put redim at the beginning or end of the first loop it doesnt fill anymore of the array.

    What can i do to run your block back to back, Thankyou in advance!

  18. #18
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    without your code being posted I'm not able to answer your question

    Why can't you have as many variables as you need?

  19. #19
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Sub thoughts()
        curMS = inputYear + " MasterSheet"
        curOOT = inputYear + " OOT DATA"
        curMI = inputYear + " MI DATA"
        Dim yval As Integer
        Dim xval As Integer
        Dim classval As Integer
        Dim a As Integer
        Dim sh As Worksheet, lrow As Long, j As Long, result
        Dim arr27, arr9, arr7, i As Long, mystr As String
        Dim crit1 As String, crit2 As String
        Dim q As Long, w As Long, e As Long
    
    'If IsError(Evaluate(curOOT & "!A1")) Then
    'this handles errors if the sheet isnt found
     '   MsgBox "Sheet " & Chr(34) & "OOT DATA" & Chr(34) & " is not found", vbCritical, "Error"
     '   Exit Sub
    'Else
        Set sh = Sheets(curOOT)
    'End If
    
    lrow = sh.Cells(Rows.Count, "a").End(xlUp).Row
    'calc the last row in the OOt sheet listed above
    
    If lrow = 1 Then
    'error handling for lacking rows
        If sh.Cells(1, 9) = "CO" And sh.Cells(1, 27) = "class 12" Then
            Sheets.Add.Range("a1").Value = sh.Cells(1, 7).Value
            Exit Sub
        End If
    End If
    
    
    ReDim result(1 To lrow, 1 To 1)
    
        For q = 0 To Sheet1.ListBox2.ListCount - 1
        arr7 = sh.Range("g1:g" & lrow) 'Factory Arr 7 for the 7th row, sets the range from g1 to g-last row
    arr9 = sh.Range("i1:i" & lrow) 'country
    arr27 = sh.Range("aa1:aa" & lrow) 'class
    crit1 = "CO"
    crit2 = "Class 11"
            xval = ((q * 3) + 4) 'offset
            'pull country from (xval,1) = country code
        'ReDim result(1 To lrow, 1 To 1)
           
            For w = 1 To 5
                    If w = 1 Then
                      yval = 18
                      crit2 = "Class 12"
                      
                      
                              For i = 1 To lrow
                If arr9(i, 1) = crit1 And arr27(i, 1) = crit2 Then
                    If InStr(mystr, " " & arr7(i, 1) & " ") = 0 Then
                        mystr = mystr & " " & arr7(i, 1) & " "
                        j = j + 1
                        result(j, 1) = arr7(i, 1)
                    End If
                End If
            Next
            If j > 0 Then
                'Application.ScreenUpdating = 0
                With Sheets(curMS)
                        .Range(.Cells(yval, xval), .Cells(yval + 2, xval)) = result
                End With
                'Application.ScreenUpdating = 1
                 End If  
                    End If
                    
                    If w = 2 Then
                     yval = 22
                      crit2 = "Class 11"
                      
                For i = 1 To lrow
                If arr9(i, 1) = crit1 And arr27(i, 1) = crit2 Then
                    If InStr(mystr, " " & arr7(i, 1) & " ") = 0 Then
                        mystr = mystr & " " & arr7(i, 1) & " "
                        j2 = j2 + 1
                        result(j2, 1) = arr7(i, 1)
                    End If
                End If
            Next
            If j > 0 Then
                'Application.ScreenUpdating = 0
                With Sheets(curMS)
                        .Range(.Cells(yval, xval), .Cells(yval + 2, xval)) = result
                End With
                'Application.ScreenUpdating = 1
                 End If 
                    End If
                    
                    If w = 3 Then
                        yval = 26
                        classval = 13
                    End If
                    
                    If w = 4 Then
                        yval = 30
                        classval = 9
                    End If
                    
                    If w = 5 Then
                        yval = 36
                        classval = 14
                    End If
        'ReDim result(1 To lrow, 1 To 1)
    
                Next
            Next
        
    End Sub

    The only way i could get it to work for more than one was how its listed above, i tried to use it as a method, i tried to put it as the third loop in but nothing would work
    :/
    Last edited by iamGreenhorn; 07-16-2014 at 12:14 PM.

  20. #20
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    I guess i should explain it,

    Im trying to run three for loops.
    1 adjusts for the X values across
    2 adjusts for the y values
    3 looks up the codes in OOT

    What im saying is if i continued the only way i can get it to work, i would need 500 variables and thats hardly a good use of anyone's time lol.
    Last edited by iamGreenhorn; 07-16-2014 at 12:15 PM.

  21. #21
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    my attempt to interpret your code (I hope I got it right mostly), press Run button or run code "thoughts" (ALT+F8, thoughts, Run)

    I suppose it's not final yet but that's what we have for now
    Attached Files Attached Files

  22. #22
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Just downloaded and Im going through it. I feel like I really bit off more than I could chew with this project.. I have a ton of other functionality to complete by the end of work today, if you can help me with this It'll really save me.. If you cant, you have already helped me and I understand..

    I really didnt wanna give out a lot of info


    So Ill also attach your file with the change I was going after, I need a for loop that grabs either the names out of the first row of cells or pulls them from the listbox and then searches OOT data and fills that.

    If theres anything else that would help let me know!
    Attached Images Attached Images
    Attached Files Attached Files
    Last edited by iamGreenhorn; 07-17-2014 at 09:30 AM.

  23. #23
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    I do not mind to help if I can. I need details then. You can omit confidential info as I did with a sample file with the same structure but meaningless data.

    In the posted file the Mastersheet contains results as they should be as I understand. Why is "candy" missing for Class 12? Do you need four first values only?

  24. #24
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Quote Originally Posted by watersev View Post
    I do not mind to help if I can. I need details then. You can omit confidential info as I did with a sample file with the same structure but meaningless data.

    In the posted file the Mastersheet contains results as they should be as I understand. Why is "candy" missing for Class 12? Do you need four first values only?
    I really need only the first few to fill the box but the data SHOULD always support that anyway..

    If you look at the picture, and if you really need I can upload the sheet, The issue is that in OOT data changes in each column. Each column is populated from the user imputed listbox then this loop needs to go through each column and find the data for the classes of the countries. I ran it one to four and tried changing the value to make it run through different countries and added fake data. In the end i will run it through to the listbox count (max 93).

    I was asked to make a template but i decided i wanted to try my hand at vba, i really didnt have the time and i kept increasing the complexity of this project lol. I guess a week isnt enough time anyway...

  25. #25
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    check below
    Attached Files Attached Files
    Last edited by iamGreenhorn; 07-17-2014 at 08:17 AM.

  26. #26
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    I will check it out and post for your review

  27. #27
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Quote Originally Posted by watersev View Post
    I will check it out and post for your review
    I have a better one for you here. one second

  28. #28
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    project.xlsm

    Here i added a little code to change the countries,

    I suggest you move all the items in the listbox from right to left with the "<<" then add a few like china, usa.. countries with lots of data then click build.

    Then navigate to module one, i think youll find everything there..
    Thanks again!

    Just noticed i removed Col A from OOT so youll need to make a row a so lrow works
    Last edited by iamGreenhorn; 07-17-2014 at 08:58 AM.

  29. #29
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    please check attachment

    I have corrected some Listboxes codes a bit, some clean up on BuildFiles code and Thoughts code has been assigned to "Fill from OOT Data" button
    Attached Files Attached Files

  30. #30
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    Works flawlessly

    You're the man. If I'm ever in the ukraine, ill buy you a beer.
    Last edited by iamGreenhorn; 07-17-2014 at 09:33 AM.

  31. #31
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    if we are done you can mark the thread as Solved as per Forum Rules. If any questions you can still make posts here afterwards, I have subscribed for it.

  32. #32
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    I was hesitant to because i didnt know if i could still post, but good to know.
    I will shortly, and i largely understand the concept of whats going on but I may have some questions

  33. #33
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    ok, cheers for now

  34. #34
    Registered User
    Join Date
    07-14-2014
    Location
    Germany
    MS-Off Ver
    2007
    Posts
    26

    Re: VBA For loop

    It seems to throw an error with but with no consistency. I have tried to labeling the variables as a static ...

    Set sh = Sheets(curOOT)
    I just piled all the code together and will built the databases first. but how do i fix that?

  35. #35
    Forum Expert
    Join Date
    11-29-2010
    Location
    Ukraine
    MS-Off Ver
    Excel 2019
    Posts
    4,168

    Re: VBA For loop

    check value of the variable cur00T and how it gets its value

    To declare sh variable:
    Dim sh as Worksheet

+ 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. HOW TO: Pause loop, fix error on a popup UserForm, continue loop
    By AndyMachin in forum Excel Programming / VBA / Macros
    Replies: 9
    Last Post: 06-19-2014, 04:37 PM
  2. [SOLVED] Copy dynamically changing column and Paste using VBA Loop (Loop within Loop)
    By nixon72 in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 02-12-2013, 12:46 PM
  3. Why did an inner loop variable start overwriting the outer loop range suddenly?
    By 111StepsAhead in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 05-16-2012, 03:24 PM
  4. Macro Loop Broken. Detects Max but doesn't continue loop
    By herchenbach in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 06-21-2011, 12:17 PM
  5. Replies: 0
    Last Post: 07-20-2010, 11:42 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