Global variable losing it's value when another button is pushed

G

Guest

Hello and thanks for any help that's provided.

I am trying to pass a primary key on one form to another form that will use
it as a foreign key. I want the value passed to be the most recent record
displayed on the initial form. I have created a module with a global
variable that is assigned the primary key value upon the 1st form's save
function. I have debugged and the value is correctly assigned.
Unfortunately when another button on the form is pressed the variable loses
it's value. Everything seems correct and this should be pretty cut and dry
but my coding skills are rusty and I'm not seeing the error.

Module:
Option Compare Database

Public lngNaBusUnitId As Long

1st Form, variable value assigned:
lngNaBusUnitId = CLng(Me.NA_BUS_UNIT_ID.Text)
 
G

Guest

Hey Joshua,

Thanks for the response, I'm including all of the button code. I apologize
for the length but there's some error trapping in there that I wasn't sure if
you wanted to see.
-------------------------------------------
Private Sub cmdSave_Click()

On Error GoTo ErrorHandler

Me.NA_BUS_UNIT_ID.SetFocus
If Me.NA_BUS_UNIT_ID.Text = "" Then
MsgBox "Please enter an ID", vbOKOnly
Me.NA_BUS_UNIT_ID.SetFocus
End
ElseIf Not IsNumeric(Me.NA_BUS_UNIT_ID.Text) Then
MsgBox "ID must be a number", vbOKOnly
Me.NA_BUS_UNIT_ID.SetFocus
End
End If

Me.NA_BUS_UNIT_CD.SetFocus
If Me.NA_BUS_UNIT_CD.Text = "" Then
MsgBox "Please enter a NA_BUS_UNIT_CD because it's a required
field", vbOKOnly
Me.NA_BUS_UNIT_CD.SetFocus
End
End If

DoCmd.Save
Me.NA_BUS_UNIT_ID.SetFocus
lngNaBusUnitId = CLng(Me.NA_BUS_UNIT_ID.Text)
Me.cmdSave.SetFocus
MsgBox "Id is " & lngNaBusUnitId, vbOKOnly
Form_Load
Form_Current

End

ErrorHandler:
Select Case Err.Number
Case 3146 'Unique Constraint violated
MsgBox "This ID already exists." & vbCrLf & "Please enter new
ID", vbOKOnly
Me.NA_BUS_UNIT_ID.SetFocus
Case Else
MsgBox "Oops: " & Err.Description & " - " & Err.Number
End Select

End Sub

--------------------------------------------------
 
J

Joshua A. Booker

Kono,

Try using Exit Sub statement instead of End. And make sure you don't set
lngNaBusUnitId in your Form_Current nor Form_Load as they may get called by
the button click.

HTH,
Josh
 
G

Guest

I used the exit sub and boom, worked perfectly. I'm not sure what the
difference is between exit and end but thanks for your help Joshua.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top