[VBA] Identify cell rows based on criteria and sum contents of corresponding cells

Joined
Jan 2, 2013
Messages
3
Reaction score
0
Hello,

I've recently started to teach myself VBA and would really appreciate some advice.

Basically, I've been working on a project and have got stuck trying to work out how to get Excel to do a particular task for me. In essence, what I want my code to do is as follows:

1) Look down column A (which contains text identifiers) and select every instance where there is a given word, say 'cat'. I think I've got this bit down ok and the code is outputting a range called FoundCells with all of these cells from column A.

2) For each of the identified columns what I'm really interested in is getting data from column B, which contains purely numeric data. I think I basically want to make a range which consists of the B column cells which correspond to the rows of FoundCells.

3) Sum the contents of the range in column B

My initial thoughts were to create some kind of variable to store the data from column B and then select it and sum, so that the pseudo code would be something like:

Dim FoundCells As Range
... (these are then found)

Dim i As Integer
Dim store As Range
Dim Sum As Integer


For i = 1 To FoundCells.Count


store(i).Value = Cells(FoundCells(i).Row, FoundCells(i).Column + 1).Value

Next


Range(store).Select


Sum = Application.WorksheetFunction.Sum(Selection)

I haven't yet managed to get this kind of sequence to work. I think (possibly among other things) I'm getting confused about object types.

At this stage I'm not too concerned with making the code very efficient but more that it's an intuitive method.

Many thanks in advance!

Sam
 
Joined
Mar 20, 2012
Messages
764
Reaction score
4
Do you need to use VBA to do this? It sounds to me like you are just looking to sum up numbers in Column B if Column A meets a criteria. If that is all you're looking for, a SUMIF formula should do for you. It sums up numbers in a target range based on a criteria range.
 
Joined
Jan 2, 2013
Messages
3
Reaction score
0
Hi alow,

Thanks very much for this reply! I've managed to sort out my problem now, and SUMIF will be a very useful function to use in the future I'm sure.

Really appreciate the help and the Calvin and Hobbes!

Sam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top