1

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!

1
  • I'm not sure what the error is you're receiving, but it does look like you need to reset the value of result for each iteration of the loop. Maybe declare and initialize result inside the loop. Commented Jun 26, 2014 at 0:58

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.