mercredi 1 mars 2017

VBA If Statement and For Loop moving to the cell below

I have 3 columns in my xlSheet

Year      GapYear   Col3
Year 13   Yes       2018
Year 12   No    
Year 13   Yes   
Year 12   No    

I want vba to work out the start year in col3 based on my if statement logic:

Sub startYear()


Dim Year As Range
Set Year = Range("A2")

Dim GapYear As Range
Set GapYear = Range("B2")

Dim Col3 As Range
Set Col3 = Range("C2")



lastRow = ActiveWorkbook.ActiveSheet.UsedRange.Rows.Count
For Row = 1 To lastRow


     If Year = "Year 13" And GapYear = "Yes" Then Col3 = "2018"
     If Year = "Year 13" And GapYear = "No" Then Col3 = "2017"
     If Year = "Year 12" And GapYear = "Yes" Then Col3 = "2019"
     If Year = "Year 12" And GapYear = "No" Then Col3 = "2018"


Next Row

End Sub

The code only works out cell C2 and doesn't move down to work out the other rows. I have tried changing the ranges to the whole column e.g. Range("C:C") but I get a type mismatch error. I have also tried adding activecell.offset(1,0) in the for loop which moves the activecell down but cell C3 remains blank.

I have hundreds of entries in columns A (Year) and B (GapYear), how can I get the code to work through each row and give the correct answer in col3?

Thanks

Aucun commentaire:

Enregistrer un commentaire