0

This is my second post in as many hours, not sure if there is a limit on how many times we can post but I was just wondering if you could figure out why this piece of code is not working?

 Dim grading As String If score <= 5 Then grading = "Good Job!" ElseIf score < 15 > 5 Then grading = "Better Luck Next Time" End If MessageBox.Show("Your Brain Age is" & score & "." & vbNewLine & vbNewLine & grading, "Brain Age") End Sub 

Basically what's happening is that when I use the variable grading in the messagebox, the following error comes up

Warning 1 Variable 'grading' is used before it has been assigned a value. A null reference exception could result at runtime.

I'm sure there is a quick and easy solution.

I want to use a string in a messagebox but cannot get it to work - check code

1
  • 1
    ElseIf score < 15 > 5 Then is not valid syntax. Is that a typo? What was it supposed to be? Commented Jul 10, 2015 at 13:26

1 Answer 1

2

To address your main question, the problem is that if none of the following conditions are met:

If score <= 5 Then grading = "Good Job!" ElseIf score < 15 > 5 Then grading = "Better Luck Next Time" End If 

... then the grading variable remains unassigned, and the compiler appropriately thinks that you didn't intend to do this.

To fix this, either initialize the grading variable with an appropriate value:

Dim grading As String = "default value" 

Or, add an else block to ensure that you always set something to grading before attempting to use it:

If score <= 5 Then grading = "Good Job!" ElseIf score < 15 > 5 Then grading = "Better Luck Next Time" Else grading = "default value" End If 

Also, you may want to revise the following:

ElseIf score < 15 > 5 Then 

... it doesn't look right. Did you mean this instead?

ElseIf score < 15 AndAlso score > 5 Then 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.