I am trying to use vba to grade the class here are my codes and information.
3 conditions, if grades are 100 or above, it will show 100+, if it's 50 or above, it will show 50+. Else, it will show below 50. I am trying to create a button in sheet2 so when I press it, the codes will run in sheet1. The range will vary every month so that is why I tried to loop to the last row in column A. I am also showing you a snapshot of the result I am trying to produce. My question is when I run the code, it has an error for else without if. Need a suggestion or advice.
Sub Macro1()
Dim I As Integer
Dim lr As Integer
Set ws = Worksheets("Sheet1")
ws.Activate
lr = Range("A" & Rows.Count).End(xlUp).Row
For I = 2 To lr
If Cells(I, 1).Value >= 100 Then Cells(I, 2).Value = "100+"
ElseIf Cells(I, 2).Value >= 50 Then Cells(I, 22).Value = "50+"
Else: Cells(I, 2).Value = "Below 50"
End If
Next I
End Sub
Thank you,
You have written the the If
statement as in-inline If
since the code to run is on the same line as the Then
statement. To use an Else
or ElseIf
you need to format it differently. Try this:
If Cells(I, 1).Value >= 100 Then
Cells(I, 2).Value = "100+"
ElseIf Cells(I, 2).Value >= 50 Then
Cells(I, 22).Value = "50+"
Else
Cells(I, 2).Value = "Below 50"
End If
This will solve your first error " else without if "
Personally, I like using Select Case for this kind of logic.
Select Case Cells(I, 1).Value
Case Is >= 100
Cells(I, 2).Value = "100+"
Case Is >= 50
Cells(I, 22).Value = "50+"
Case Else
Cells(I, 2).Value = "Below 50"
End Select
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.