I have a Excel VBA function which gives the grading of a student in the B column based on the marks in the A column. I tried with FOR NEXT and it worked fine but when I tried with DO While it showed error. Where is the issue?
Private Sub Button2_Click()
Dim mark As Single
Dim grade As String
Dim counter As Integer
counter = 1
Do While counter < 10
counter = counter + 1
mark = Cells(counter, 1).Value
'To set the alignment to center
Range("A1:B10").Select
With Selection
.HorizontalAlignment = xlCenter
End With
Select Case mark
Case 0 To 20
grade = "F"
Cells(counter, 2) = grade
Case 20 To 29
grade = "E"
Cells(counter, 2) = grade
Case 30 To 39
grade = "D"
Cells(counter, 2) = grade
Case 40 To 59
grade = "C"
Cells(counter, 2) = grade
Case 60 To 79
grade = "B"
Cells(counter, 2) = grade
Case 80 To 100
grade = "A"
Cells(counter, 2) = grade
Case Else
grade = "Error!"
Cells(counter, 2) = grade
End Select
Loop
End Sub
You can take any values between 0 to 100 in the first 10 rows of excel sheet A column. When you run the macro the B cell gets filled with gradings.
Try below. The code writes grade on next row as counter is increased before grade is written to the row cell. I moved the statement
counter = counter + 1
after select case, now all the rows get corresponding grade.your code works for me. since you want to slop through the first 10 rows you have to set counter=0 at the beginning, or not to set it at all furthermore you can shorten it down :