简体   繁体   中英

Looped If/Then Functions in Excel VBA

I'm just starting to learn Excel VBA and I'm running into problems with a particular exercise. Given a column of 20 randomly generated integers between 0 and 100 in a column, I want to write a VBA program that writes in the column next to it "pass" if the number is greater than or equal to 50 and "fail" if the number is less than 50.

My approach involved using a looping function from i = 1 to 20 with an If statement for each cell (i,1) which would write pass or fail in (i,2).

Sub CommandButton1_Click()
'Declare Variables
Dim score As Integer, result As String, i As Integer

'Setup Loop function, If/Then function
For i = 1 To 20
    score = Sheet1.Cells(i, 1).Value
    If score >= 60 Then result = "pass"
    Sheet1.Cells(i, 2).Value = result
Next i

End If
End Sub

Could I get some insight into what I'm doing wrong?

Thanks in advance!

Try something like this...

Sub CommandButton1_Click()
'Declare Variables
Dim score As Integer, result As String, i As Integer

'Setup Loop function, If/Then function
For i = 1 To 20
    score = Sheets("Sheet1").Cells(i, 1).Value
    If score >= 60 Then
        result = "pass"
    Else
        result = "fail"
   End If
    Sheets("Sheet1").Cells(i, 2).Value = result

Next i

End Sub
  1. You need to properly specify the worksheet your working with like Sheets("Sheet1").Cells(...

  2. Add an else clause to set result to fail when the value is less than 60. otherwise it never changes after the first 'pass'

  3. Move the End if inside the for loop, immediately after the score check...

The correction with the least amount of changes is the following :

Sub CommandButton1_Click()
'Declare Variables
Dim score As Integer, result As String, i As Integer

'Setup Loop function, If/Then function
For i = 1 To 20
    score = Sheet1.Cells(i, 1).Value
    If score >= 60 Then 
        result = "pass"
        Sheet1.Cells(i, 2).Value = result
    End If
Next i

End If
End Sub

Keep in mind that, in VBA, variables are global to the function; not local to the loop. As it was mentionned, you could also have wrote something like :

result = ""
if score >= 60 then result = "pass"
sheet1....

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM