Reputation: 3
I have a sub with two variables in a module. When called from the form, the second variable triggers the error "“Variable 'ala1' is used before it has been assigned a value. A null reference exception could result at runtime”. The result is a blank textbox. Would appreciate your help to find where my code is not correct. Here is my code:
Module1
Dim N10, N02b, A6, N07 As Double
Public Sub AxlPos(ByVal axl As Double, ByVal axla As String)
If axl > (N10 - N02b / 1000) * modCos(A6) + N07 Then
axla = "in section 1"
ElseIf axl > (N10 - N02b / 1000) * modCos(A6) Then
axla = "in section 2"
ElseIf axl > (N10 / 1000) * modCos(A6) Then
axla = "in section 3"
Else
axla = "in section 4"
End If
End Sub
Form1
Dim N10, N02b, A6, N07, al1 As Double
Dim ala1 as string
Private Sub btnSolve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSolve.Click
axlpos(al1,ala1)
Txtala1.Text = ala1
End sub
Upvotes: 0
Views: 38
Reputation: 216293
I suggest you to change your sub to a function returning a string.
Dim N10, N02b, A6, N07 As Double
Public Function AxlPos(ByVal axl As Double) as String
Dim axla As String
If axl > (N10 - N02b / 1000) * modCos(A6) + N07 Then
axla = "in section 1"
ElseIf axl > (N10 - N02b / 1000) * modCos(A6) Then
axla = "in section 2"
ElseIf axl > (N10 / 1000) * modCos(A6) Then
axla = "in section 3"
Else
axla = "in section 4"
End If
return axla
End Sub
And then call the function with
Dim N10, N02b, A6, N07, al1 As Double
Private Sub btnSolve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSolve.Click
Txtala1.Text = axlpos(al1)
End sub
The error is caused by the fact that at the point in which you call the method AxlPos
the variable passed to the method (ala1
) has not been assigned. The compiler warns you that this could cause a null reference exception in the code.
However it seems that you want to set the passed variable to a different value based in your calculations so the best approach is to create a function the return the calculated string value.
If you still want to use your approach then your code should be changed to
Private Sub btnSolve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSolve.Click
ala1 = String.Empty
axlpos(al1,ala1)
Txtala1.Text = ala1
End sub
but more important you should change the ByVal
in a ByRef
in the called module method
Public Sub AxlPos(ByVal axl As Double, ByRef axla As String)
See ByVal vs ByRef clarification
Upvotes: 3