If you use Excel>=2007 take a look to SUMIFS function or else to SUMPRODUCT.