Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Excel/VBA: Programming IF statements for a range of cells

Status
Not open for further replies.

CarlosDiaz

Computer
Aug 1, 2002
2
0
0
US
I'm trying to program IF statements for an unkown number of cells, that changes every time a new input file is used.

My problem is that the number of rows the IF statement needs to be
repeated in changes everytime. Every input file has a different number
of rows in it.

I have a column heading named Cost For Roads with an unknown number of
roads and costs associated with those roads. Then I have Cost for
Crossings in the same column with an unknown number of crossing and
costs associated with each crossing.

Could I somehow count the number of cells below Cost For Roads that
contain a number and stop the counter when I hit the cell that contains
the text Cost For Columns. That way I would know the number of rows that
I would need to copy the IF statement for. And then repeat the same for
columns, except stop the counter when I hit a blank cell.

How could I write a subroutine that counts the number of cells that are roads(that need to be a certain IF statement) and then create the IF statement and apply it to all those cells. Therefore, find x and apply the IF statement to x rows. The same would need to be done for the crossings, a different IF statement.

Any help on this would be greatly appreciated.

Carlos
 
Replies continue below

Recommended for you

You have a couple of possibilities.

There is the MATCH function, which returns the relative position of the target within the search region.

Alternately, you can brute force your way down the column, one cell at a time and checking to see if the next cell contains your target.

TTFN
 
CarlosDiaz:

If you have "Cost For Roads" in Cell A1 and the costs listed below (in column A), the following command will count the number of entries in column A and subtract one (since you don't want to count the heading) and store it to the variable X:

X = WorksheetFunction.CountA(Columns("A:A")) - 1

Now, if you want to use conditional formating on each cell I would write a for-next statement to loop through all the cells in which you want to use the If statement:

For RoadCostIndex = 1 to x
If Cells(1,RoadCostIndex + 1).Value <= 50000 then
Cells(2,RoadCostIndex + 1).Value = &quot;Ok&quot;
Else: Cells(2,RoadCostIndex + 1).Value = &quot;Not Ok&quot;
End If
Next RoadCostIndex

Hope this helps!

jproj
 
Status
Not open for further replies.
Back
Top