+ Reply to Thread
Results 1 to 29 of 29

Loop macro through all columns of worksheet

  1. #1
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Loop macro through all columns of worksheet

    Hello all

    I have this code which is intended to perform a required task: build a single, 2-column list from the filtered results of one (or several worksheets) from another workbook.

    The macro that I have built performs the task as required, but my code makes specific reference to the 1st column of data within the source sheet, so the macro only performs the task for the 1st column.

    How can I change the code so that it repeats the process for each subsequent column across the worksheet until it reaches the end (either a blank cell in row 1 OR the end of the sheet)? I have marked the 2 sections of the code that reference a specific column using comments containing ********** and ++++++++++ respectively.

    The 2nd item on my wish-list (although I will be more than happy if I can only have the above) is to then repeat the process through a further 9 specified worksheets within the same workbook as each sheet is completed (I have marked this part of the code with //////////).

    I have spent a whole lot of time investigating this and experimenting and I have previous posts which were unsuccessful. I am desperately hoping that there is someone out there who can come to my rescue as my next approach is going to have to be extremely manual.

    Please Login or Register  to view this content.
    Any thoughts???
    Last edited by Berries; 06-18-2010 at 08:24 AM.

  2. #2
    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: Loop macro through all columns of worksheet

    Hi Berries

    I have no way to test it but try this code and see if it does as you described
    Please Login or Register  to view this content.
    Place the names of your sheets in the array.

    John
    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.

  3. #3
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Hello John

    Thanks heaps for your response - I am quite excited that I might actually be getting close to getting somewhere.

    I have tried your code, but I keep coming up with this error when I run it:

    Compile Error: Invalid or unqualified reference.
    I have also tried to make adjustments but have not had any success.

    I have attached the spreadsheet containing the macro and a simplified version of the Materials Schedules workbook containing only one of each schedule type in the hope that you might be able to see what is going on.

    Optimistic anticipation on this end....

    Tony

  4. #4
    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: Loop macro through all columns of worksheet

    Hi Berries

    It's late here tonight. I'll look at this tomorrow.

    John

  5. #5
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    That's fantastic thanks very much John.

  6. #6
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Loop macro through all columns of worksheet

    Although the macro could use a major rewrite to remove all the selecting and activating, addressing the commands directly to the ranges in questions, try just fixing this for now:
    Please Login or Register  to view this content.
    _________________
    Microsoft MVP 2010 - Excel
    Visit: Jerry Beaucaire's Excel Files & Macros

    If you've been given good help, use the icon below to give reputation feedback, it is appreciated.
    Always put your code between code tags. [CODE] your code here [/CODE]

    ?None of us is as good as all of us? - Ray Kroc
    ?Actually, I *am* a rocket scientist.? - JB (little ones count!)

  7. #7
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Loop macro through all columns of worksheet

    PASSWORD protected file...

  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: Loop macro through all columns of worksheet

    Hi Berries

    I've modified the code somewhat based on the actual structure of your worksheets
    Please Login or Register  to view this content.
    A couple of things...the code assumes your data starts in Column J as you inferred in your original post. However, in the workbook you posted, data appears to start in Columns J, G and H. Is this the case or am I looking at it wrong?

    Second thing...the code halts at
    Please Login or Register  to view this content.
    That's why these lines are commented out. Your named range "Code Required" appears to be empty.

    I'm not sure what you're trying to do here but the code does what it's written to do.

    Let me know of issues.

    John

  9. #9
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Loop macro through all columns of worksheet

    99 times out of 100, this line of code will do what you want:
    Please Login or Register  to view this content.
    But that's not really a reliable use of UsedRange function. There's a hidden flaw most people won't run into, and when they finally do they won't understand what's gone wrong.

    UsedRange.Columns.Count means "tell me how many columns have data", not "tell me what the last column is".

    Using the function the way you're using it is only accidentally giving you the correct answer. More simply, if you skip any rows at the top of your worksheet or columns on the left, the code may no longer give the correct answer.

    You want to see this problem in action...

    1) Open a blank worksheet
    2) Put some data in C3 and no where else

    Now try your command code and you'll see that it reports the Last Row and/or the Last Col is 1 instead of the expected 3.

    Because of this, I never rely on the USEDRANGE.COLUMNS.COUNT method.

    ===========
    This has been a public service announcement brought to you by Calgon...."take me away"

  10. #10
    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: Loop macro through all columns of worksheet

    Hi JBeaucaire

    Thanks for the "slap upside the head".

    I've read of the caveats using
    Please Login or Register  to view this content.
    and I appreciate your feedback. What I was attempting to do here was count the number of Columns on Row 1 that have data beginning in Column 10 to the right. This didn't work
    Please Login or Register  to view this content.
    it gave me a false answer . Also, this didn't work
    Please Login or Register  to view this content.
    After a couple of hours of not being able to figure out why, I resorted the "offending" code.

    You may or may not believe that I've rewritten this post because, in writing the original version, I had an "Aha" moment. "Right" vs "Left"? Sometimes I'm dyslexic like that.

    Thanks again for your feedback.

    John

  11. #11
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Hello John & JBeaucaire and thanks to you both for your contributions.

    John - regarding your 2 points at the bottom of your post containing the new code:
    A couple of things...the code assumes your data starts in Column J as you inferred in your original post. However, in the workbook you posted, data appears to start in Columns J, G and H. Is this the case or am I looking at it wrong?
    - You are correct, I had initially thought that I may be able to reference different columns to start but I have now changed the workbook so that all sheets have data starting in column J. I have attached the new file.

    Second thing...the code halts at
    Please Login or Register  to view this content.
    That's why these lines are commented out. Your named range "CodeRequired" appears to be empty.
    - Sorry, my mistake here. I did not update the reference in this named range when I made a change to 1 of the other ranges. The "CodeRequired" range is the range between the other 2 named ranges that needs to have the contents of Column 1 copied down. I have corrected this now and it is also in the new file.

    I can feel that we are very close but there are a couple of issues:
    1. The code doesn't recognise the actual last cell containing data IN ROW 1. The process continues until column IM, which is 9 columns before the end of the sheet. This happens regardless of whether the data in row 1 continues to the end or finishes earlier. I assume this has to do with the fact that there is data in other parts of the column even if row 1 is empty. I experimented for quite a while trying to resolve this and had success with a dynamic named range but this only worked for the 1st sheet.

    2.The part of the code that runs an auto-filter:
    Please Login or Register  to view this content.
    is actually filtering 5 columns ahead of the intended column. eg Instead of filtering column J, it is filtering 5 columns ahead at column O and so on.

    I have spent most of the day experimenting with this to see if I could find a resolution, but I have ended up back at the start.

    John - you mentioned that you have spent quite a bit of time on this and I am very grateful for all of your efforts. I am hoping that these couple of problems are straight-forward and easily resolved.

    Cheers

    Tony

  12. #12
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Loop macro through all columns of worksheet

    Here are my two favorite techniques for spotting the last column accurately. The first YOU pick which row to look across, the second simply finds the last column of data by examining all columns.

    Please Login or Register  to view this content.

    John, as you guys continue to work with this macro, I believe your results will improve if you can edit out all the "selections" and simply address your commands to the rows/columns directly.
    Last edited by JBeaucaire; 06-23-2010 at 09:35 AM.

  13. #13
    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: Loop macro through all columns of worksheet

    Hi Berries

    Try this code; it appears to be doing as it should.
    Please Login or Register  to view this content.
    Please note, I had to unprotect the sheets to make some things work. I didn't set protection back on. You may wish to do that. Let me know of issues.

    John

  14. #14
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Loop macro through all columns of worksheet

    Another option you can use instead of unprotecting a worksheet, you can update the existing protection to ADD the ability for your macro to run freely even though the sheet is protected. The UserInterfaceOnly parameter makes it so the protection only applies to humans, not to VBA.

    Please Login or Register  to view this content.
    Use this at the top instead of unprotecting.


    NOTE: The UserInterfaceOnly setting disappears when you close the workbook, it must be set at least once again when the workbook is opened again, or just include it in your macros as shown.

  15. #15
    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: Loop macro through all columns of worksheet

    Hi JB

    Actually, Berries has this workbook open code
    Please Login or Register  to view this content.
    so I'm not certain why I had issues with some of the code not executing properly. Unprotecting the worksheet fixed the problems I was having so I ran with that.

    I'm fairly certain we're not done yet so I'll try to resolve the issue in the next rewrite.

    Thanks for your feedback.

    John

  16. #16
    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: Loop macro through all columns of worksheet

    Hi Tony

    I found a bit of a bug. The procedure is picking up an extra record for each sheet. I believe I know the fix. I need you to look the data over carefully and see if you find other issues.

    Change this line of code
    Please Login or Register  to view this content.
    to this
    Please Login or Register  to view this content.
    and this should fix the bug I found.

    I'm going to be traveling this week and weekend, so I may or may not get time to look at this. But get back to me with issues you see.

    John
    Last edited by jaslake; 06-23-2010 at 11:30 PM. Reason: Add Code

  17. #17
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    This is fantastic!
    I had something come up this afternoon and so haven't completely finished testing it as yet, but I will make sure that I do so tomorrow.

    The code works perfectly for the simplified version of the workbook that we have been using. I got as far as making the necessary changes to run it for the complete workbook but then hit an error when I ran it and was pulled away before I had a chance to have a proper look at the cause.

    I did need to make one change from:
    Please Login or Register  to view this content.
    to
    Please Login or Register  to view this content.
    as the filter was missing row 4.

    John, regarding your note that you had to unprotect the sheets - this is fine, as once we have finalised the code I will have the macro close the workbook without saving changes.

    Thanks again and I will let you know how I go.

  18. #18
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    I hadn't seen this post before my last post but not surprisingly you were a step ahead of me with this one.

  19. #19
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Hello John

    I have tested the results extensively with the full workbook and it works a charm but for this issue,
    If the cell being filtered only contains 1 row of data, then this part of the procedure:
    Please Login or Register  to view this content.
    selects the entire rest of the column rather than only the intended single cell containing data and then produces an error when it tries to paste that selection. I tried to improve the above by using the
    lastrow
    variable that you have created but I couldn't get it to work. There seems to be an exception to this error if it happens on the 1st sheet. I intentionally included some columns early on in the 1st sheet that contained only 1 row of data and the procedure was able to continue as normal.

    There is 1 other thing that I need to be able to do - have the name of the respective source worksheet pasted into the 3rd column. (So that is 2 columns over from the "CodeRequired" named range). I haven't mentioned this before now as I didn't want to complicate the thread any more than necessary in the early stages and I hope that it doesn't require a change to what you have already done.

    I am very excited about this John.

    I will also be away for the next 3 days and so won't be able to check in until Tuesday morning my time. Enjoy your weekend!

  20. #20
    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: Loop macro through all columns of worksheet

    Hi Berries

    I'll try to look at this in the next day or two. My children and grand children are coming to visit for the Holiday so I may not get right on it.

    You might show me an example of this
    have the name of the respective source worksheet pasted into the 3rd column
    I'll get back to you.

    John

  21. #21
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Hi John

    Column A is populated with a combination of:
    Please Login or Register  to view this content.
    and later:
    Please Login or Register  to view this content.
    Column B is populated with (Subject to improvement per my previous post):
    Please Login or Register  to view this content.
    What I am hoping for is a way to also have column C populated with the name of the worksheet (eg. A category materials 1 or B category materials 1) that the data in each row has originated from. The reason for this is so that I can use formulae to extract the additional information that I need from each of the relevant worksheets.

    I hope that this makes sense.

    Thanks John, and have a great time with your family. I will also be heading north on the weekend to see my family- they are taking me away for a couple of days so I will be offline until Tuesday night my time.
    Last edited by Berries; 07-01-2010 at 07:59 PM.

  22. #22
    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: Loop macro through all columns of worksheet

    Hi Berries

    See if this code solves the problem you were having and if it satisfies regarding the file name in column C
    Please Login or Register  to view this content.
    Please Login or Register  to view this content.
    Let me know of issues.

    John

  23. #23
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Hi John - sorry for the delay in replying but I have just gotten back to civilisation.

    I have tested your new code on the workbook that I had emailed to myself for this purpose, and everything seems to be working perfectly.

    I won't be back at work until Monday and so I will do the full and extensive testing on my full workbook then.

    The only thing that I changed is from :
    Please Login or Register  to view this content.
    to:
    Please Login or Register  to view this content.
    because if there is no data in any given column then I just want the procedure to continue on to the next column.

    Everything else looks great John. I will let you know how it all goes on Monday.

  24. #24
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Hi John

    All bugs are now ironed out and the code does everything that I need it to do!

    What you have done is absolutely sensational and I very much appreciate your time.

    People like yourself make sites like this an amazing resource and I am learning in leaps and bounds.

    For my own curiosity, what does the
    Please Login or Register  to view this content.
    achieve? I note that it is used after the 1st copy and paste procedure but not after the next 2.


    Cheers John and all the best

    Tony

  25. #25
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Re: Loop macro through all columns of worksheet

    Avoid using select and activate in VBA-code.
    Use Usedrange to determine the number of used columns/rows.
    Use specialcells(2) to identify cells with values in it.
    I think you don't need autotfilter.
    Most of the time 'copying' values can be done more easily (and faster)
    with e.g. range("K2")=range("B7"). (to copy cell B7 to cell K2)

  26. #26
    Forum Expert JBeaucaire's Avatar
    Join Date
    03-21-2004
    Location
    Bakersfield, CA
    MS-Off Ver
    2010, 2016, Office 365
    Posts
    33,492

    Re: Loop macro through all columns of worksheet

    Quote Originally Posted by snb View Post
    Avoid using select and activate in VBA-code.
    Agreed.


    Quote Originally Posted by snb View Post
    Use Usedrange to determine the number of used columns/rows.
    I can never recommend this technique. There is a hidden flaw in the UsedRange method that will eventually bite you.

    To see the flaw in action, open a new workbook, put a value in cell F5 only, then try your UsedRange technique to get the LastRow with data, you will get an answer of 1 instead of 5. This means your macro can be failing and you don't even know it.

    Simplest way to always get the last row is to examine the column in question specifically, or do a generic "search all rows for the last row of data"...here are the two I always use now:
    Please Login or Register  to view this content.


    Quote Originally Posted by snb View Post
    Use specialcells(2) to identify cells with values in it.
    If you want people to have no clue what your code is doing at this point, use SpecialCells(2). If you want them to at least be able to read it the first time through without wondering, use SpecialCells(xlConstants).

    There are a LOT of shortcuts to make code take fewer letters and people use them, but they typically make the code a LOT more difficult to understand. Since this is a teaching forum, I use them less and less every day.


    Quote Originally Posted by snb View Post
    I think you don't need autofilter.
    AutoFilter is almost always faster at collecting data than going row by row or cell by cell.


    Quote Originally Posted by snb View Post
    Most of the time 'copying' values can be done more easily (and faster)
    with e.g. range("K2")=range("B7"). (to copy cell B7 to cell K2)
    Absolutely.
    Last edited by JBeaucaire; 07-12-2010 at 11:00 AM.

  27. #27
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Re: Loop macro through all columns of worksheet

    Since this is a teaching forum
    That's why I try to give 'intriguing' suggestions, which the OP has to explore further if interested. If not, a fast-food solution won't contribute to his/her 'learningprocess' either.

  28. #28
    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: Loop macro through all columns of worksheet

    Hi Berries
    Regarding this
    Please Login or Register  to view this content.
    the line of code clears the clipboard of data. I've always been of the impression that you only needed the line of code once in the procedure to clear the clipboard; however, since you asked the question, I researched it further and can no longer find that reference. In fact, most advise that you include the line of code after each copy/paste action.

    Glad the code works for you. Thanks for the "Style" points.

    John

  29. #29
    Registered User
    Join Date
    02-15-2009
    Location
    Melbourne, Australia
    MS-Off Ver
    Excel 2003
    Posts
    22

    Re: Loop macro through all columns of worksheet

    Thanks all.

+ 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