user3777202
user3777202

Reputation: 21

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!

Upvotes: 1

Views: 1295

Answers (2)

rivworks
rivworks

Reputation: 26

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...

Upvotes: 1

Bernard Saucier
Bernard Saucier

Reputation: 2270

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....

Upvotes: 0

Related Questions