Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "if then" statements inside a "for" loop in Microsoft VBA

Tags:

excel

vba

I am trying to pull numerical grade values and convert them into a string which will represent the grade, A >90, B >80, and so on. I planned to use a for loop to gather the values from the spreadsheet and then if then statements to assign the letter designation. Here is the code I have so far.

 For i = 1 To 11
' Pull Grade numerical value
    Grade = Cells(2 + i, 16).Value
' Assign Numerical Value a script Grade
    If Grade > 60 Then
        Letter = "D"
    If Grade > 70 Then
        Letter = "C"
    If Grade > 80 Then
        Letter = "B"
    If Grade > 90 Then
        Letter = "A"
    Else
        Letter = "F"
    Exit
' Print the letter grade
    Cells(2 + i, 17).Text = Letter
    Next i

I keep getting errors either pertaining to "Exit" or to "Next i". I have tried using "End" statements as well but that didn't fix the problems either.

like image 527
Austin G Avatar asked Nov 28 '22 05:11

Austin G


1 Answers

Or just use a formula in column Q:

=IF(P:P>=90,"A",IF(P:P>=80,"B",IF(P:P>=70,"C",IF(P:P>=60,"D","F"))))

so it updates automatically and you don't need to use VBA.


Alternatively you can add a sheet named GradeList with the following data

enter image description here

and use

=INDEX(GradeList!B:B,MATCH(P:P,GradeList!A:A,1))

as formula. This way you can easily edit the numbers/grades later, and it will pick the correct grades automatically:

enter image description here

like image 73
Pᴇʜ Avatar answered Dec 22 '22 09:12

Pᴇʜ