简体   繁体   中英

Excel VBA - Looping to count cell values larger than / smaller than specific value

I'm currently working with a large amount of contract lists. Each list is in a separate worksheet for each year's quarter and it needs to stay that way. Eg: 2007_Quarter1 , 2007_Quarter2 , etc. I have 10 years of data, so 40 quarter report worksheets.

Now I need to code a vba routine that would do the following, in the specified order:

  1. In each quarter report worksheet, run through the column containing contract values; then
  2. Count all values between 0 and 10,000; then
  3. Count all values between 10,001 and 25,000; and so on

  4. Then, when there are no more contract values in the range (which will vary from sheet to sheet), go to the next worksheet and repeat the procedure.

All results should be returned in a worksheet (let's call it Worksheets("Report")) in a table where rows are for value intervals (eg 0 to $10,000) and columns are for quarters (eg 2007 Q1, 2007 Q2, etc.).

One particular aspect of my problem is that, for practical reasons, I'd prefer to set the control intervals' min and max values in a table contained in another worksheet ("Variables"), where, for example, I'd have all minimum values in range C4 down and all maximum values in range D4 down.

For each contract value, an "If" condition should look like:

If ContractVal > Worksheets("Variables").Range("C4").Value And 
If ContractVal < Worksheets("Variables").Range("D4").Value Then ...

So far I'm having no success at coding this efficiently. I suspect some loop would work but I can't find a way to make it happen. A loop would do:

In 2007_Quarter1 ws: For each cell from A4 down to the end, count values included between Range("C4").Value and Range("D4").Value

Then for each cell from A4 down to the end, count values included between Range("C5").Value and Range("D5").Value

... and so on, then repeat for 2007_Quarter2, 2007_Quarter3, and so on.

I need rescue! Thanks in advance!

If it is ok to you to prepare the resulting matrix manually (intervals in rows and quarters in columns) you could write a macro that read the right file and count the contracts in the right range for every cell in the matrix.

If you want to build the matrix automatically you should tell the macro the year range. Then you can write a loop that read the ranges and for every range you write a loop to read every file in the right order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM