How to validate values in a column matching a set of values using excel vba

时间:2017-04-24 17:25:19

标签: excel vba excel-vba validation

Please see the below two image Sheet 1 and Sheet 2

Sheet 1 enter image description here

Sheet 2 enter image description here

I am trying to validate values in Sheet 1 "Color" column, that is if the Sheet 1 "Type" is car then the color can only be Black and White.Sheet 2 has the rules for what type , which colors can be valid. If any other color is there in sheet 1 for type Car then adjacent column should say "Color mismatch".

    for each cell in (sheet 1 - column color) 
     get type from (sheet 1 - column Type)
    check if (Sheet 1 - column Type) is in (sheet 2 column Type), 
if not give error in adjacent cell "No type"
    if (Sheet 1 - column Type) is in (sheet 2 column Type) then 
Check if (Sheet 1 - column color) has the valid color
 if not give error "color not matching"

Could any one tell me how to do this is in excel VB.

P.s, I know how to do this using countifs , but just want to know how this is done in Excel VB

Thank you.

1 个答案:

答案 0 :(得分:1)

You don't need VBA. You can use simple formula in sheet1 cell E2 (and drag down):

=IF(COUNTIFS(Sheet2!$A$1:$A$1000,Sheet1!D2,Sheet2!$C$1:$C$1000,Sheet1!A2)=0,"color not matching","color OK")