Results 1 to 6 of 6

Thread: Beginner Needing Suggestions

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Apr 2004
    Location
    Alabama
    Posts
    126

    Beginner Needing Suggestions

    Hi, I have some working code but would like to code it a little better than i'm currently doing. I'm using VB 6.0. I know that making the code Object Oriented would be better but i'm not there yet and hope t be in the near future. Please give me your suggestions. Thanks!

    This is just one of many procedures. But the suggestions that you give me will likely help me in other areas. Thanks!

    VB Code:
    1. Private Function SearchEmployeeDatabase(sFirstName As String, sLastName As String, sBadge As String, sDepartment As String, sCenter As String, sDate As String) As Integer
    2.  
    3. 'Declarations Section
    4. Dim adoConnection As ADODB.Connection    'Used to establish connection with the Employee Database
    5. Dim adoRecordset As ADODB.Recordset      'Used to query the Employee table
    6. Dim connString As String                 'Stores connection string
    7. Dim SQLstr As String                     'Stores query
    8. 'Dim iEmployeeID As Integer              'Stores the Employee's ID in Database
    9. Dim iResponse As Integer                 'Stores response from message box
    10. Dim boolSaveToDB As Boolean              'Stores value indicating whether to save to DB or not
    11. Dim x As Integer                         'Counter for For Loop
    12. Dim sPreviousLastName As String          'Used in case of change in last name
    13.  
    14. On Error GoTo AdoErrors
    15. 'Establish connection with FAE database
    16. Set adoConnection = New ADODB.Connection
    17.  
    18. connString = "Provider=microsoft.jet.oledb.4.0;Data source=" & App.Path & "\FAEDB2.2.mdb; Jet OLEDB:Database password=f.a.e.1.0"
    19.  
    20. adoConnection.Open connString
    21.  
    22. 'Verifies database connection
    23. If adoConnection.State = adStateOpen Then
    24.      'Debug.Print "Connection was established"
    25.  
    26.    SQLstr = "SELECT * From Employees WHERE BadgeNumber='" & sBadge & "'"
    27.          
    28.    'Create Recordset Object and Search Employee Database
    29.    Set adoRecordset = New ADODB.Recordset
    30.  
    31.    With adoRecordset
    32.         .Open SQLstr, adoConnection, adOpenKeyset, adLockOptimistic, adCmdText
    33.    
    34.    'Gather employee information
    35.    If .RecordCount = 1 Then
    36.      
    37.       If .Fields("FName").Value = sFirstName And .Fields("LName").Value = sLastName Then
    38.         'If this is the same name,Do all of this
    39.         gbDuplicatedBadge = False
    40.      
    41.         'Stores Employee ID in variable
    42.         gEmployee.EmployeeID = .Fields("EmpID").Value
    43.      
    44.         'Check to see if user has changed departments or centers
    45.         If .Fields("DeptID").Value = cboDepartment.ItemData(cboDepartment.ListIndex) Then
    46.             'Do nothing
    47.         Else
    48.             'Department changed. Save new department value to DB
    49.             .Fields("DeptID").Value = cboDepartment.ItemData(cboDepartment.ListIndex)
    50.         End If
    51.          
    52.         If .Fields("CenterID").Value = cboCenter.ItemData(cboCenter.ListIndex) Then
    53.             'Do nothing
    54.         Else
    55.             'Center changed. Save new department value to DB
    56.             .Fields("CenterID").Value = cboCenter.ItemData(cboCenter.ListIndex)
    57.         End If
    58.         .Update
    59.         .MoveNext
    60.  
    61.       ElseIf .Fields("FName").Value = sFirstName Then 'Assumes a possible change in last name
    62.         'Ask if user's last name changed.
    63.         iResponse = MsgBox("This badge number is already in use. Has your last name changed?", vbQuestion + vbYesNo, "Duplicated Badge Numbers")
    64.         If iResponse = vbNo Then
    65.             iResponse = MsgBox("Someone is already using this badge number. Would you like to make corrections?", vbExclamation + vbYesNo, "Duplicated Badge Numbers")
    66.             If iResponse = vbNo Then
    67.                 'Show message box if user does not change badge numbers.
    68.                 MsgBox "A note will be placed on your exam printout. Please send a copy to the PI Department so that the duplicated badge numbers can be resolved.", vbInformation + vbOKOnly, "Duplicated Badge Numbers"
    69.                 gbDuplicatedBadge = True
    70.                 boolSaveToDB = True
    71.             Else
    72.                 gbDuplicatedBadge = False
    73.                 boolSaveToDB = False
    74.                 txtBadge.SetFocus
    75.                
    76.                 'Close recordset and connection
    77.                 adoRecordset.Close
    78.                 Set adoRecordset = Nothing
    79.                 adoConnection.Close
    80.                 Set adoConnection = Nothing
    81.                
    82.                 SearchEmployeeDatabase = vbCancel
    83.                 Exit Function
    84.             End If
    85.         Else
    86.             Do
    87.             'Prompt user to enter previous last name
    88.             sPreviousLastName = InputBox("Please enter your previous last name and press enter.", "Changing Last Name")
    89.            
    90.             Loop While sPreviousLastName = ""
    91.            
    92.             sPreviousLastName = FormatText(sPreviousLastName)
    93.            
    94.             'Check user's previous last name with last name in DB
    95.             If UCase(sPreviousLastName) = UCase(.Fields("LName").Value) Then
    96.                 'Place code here that will update last name
    97.                 adoRecordset!lname = sLastName
    98.                 adoRecordset.Update
    99.                 adoRecordset.MoveNext
    100.                
    101.                 MsgBox "Your last name has been updated!", vbInformation + vbOKOnly, "Duplicated Badge Numbers"
    102.                 boolSaveToDB = False
    103.             Else
    104.                 MsgBox "There is no record of " & sPreviousLastName & " in the database.", vbExclamation + vbOKOnly, "Changing Last Name"
    105.                 boolSaveToDB = False
    106.                
    107.                 'Close recordset and connection
    108.                 adoRecordset.Close
    109.                 Set adoRecordset = Nothing
    110.                 adoConnection.Close
    111.                 Set adoConnection = Nothing
    112.            
    113.                 SearchEmployeeDatabase = vbCancel
    114.             End If
    115.         End If
    116.       Else
    117.         'Ask if user would like to change badge number.
    118.         iResponse = MsgBox("Someone is already using this badge number. Would you like to make corrections?", vbExclamation + vbYesNo, "Duplicated Badge Numbers")
    119.         If iResponse = vbNo Then
    120.             'Show message box if user does not change badge numbers.
    121.             MsgBox "A note will be placed on your exam printout. Please send a copy to the PI Department so that the duplicated badge numbers can be resolved.", vbInformation + vbOKOnly, "Duplicated Badge Numbers"
    122.             gbDuplicatedBadge = True
    123.             boolSaveToDB = True
    124.         Else
    125.             gbDuplicatedBadge = False
    126.             boolSaveToDB = False
    127.             txtBadge.SetFocus
    128.            
    129.             'Close recordset and connection
    130.             adoRecordset.Close
    131.             Set adoRecordset = Nothing
    132.             adoConnection.Close
    133.             Set adoConnection = Nothing
    134.                
    135.             SearchEmployeeDatabase = vbCancel
    136.             Exit Function
    137.         End If
    138.       End If
    139.    ElseIf .RecordCount > 1 Then
    140.         'Ask if user would like to change badge number.
    141.         iResponse = MsgBox("Someone is already using this badge number. Would you like to make corrections?", vbExclamation + vbYesNo, "Duplicated Badge Numbers")
    142.         If iResponse = vbNo Then
    143.             'Show message box if user does not change badge numbers.
    144.             MsgBox "A note will be placed on your exam printout. Please send a copy to the PI Department so that the duplicated badge numbers can be resolved.", vbInformation + vbOKOnly, "Duplicated Badge Numbers"
    145.                        
    146.             'Check to see if one of the duplicated badge numbers belong to user.
    147.             For x = 0 To .RecordCount - 1
    148.                If .Fields("FName").Value = sFirstName And .Fields("LName").Value = sLastName Then
    149.                   'If one of the names match, do this
    150.                   'Stores Employee ID in variable
    151.                   gEmployee.EmployeeID = .Fields("EmpID").Value
    152.            
    153.                   gbDuplicatedBadge = True
    154.                  
    155.                  
    156.                   'Check to see if user has changed departments or centers
    157.                   If .Fields("DeptID").Value = cboDepartment.ItemData(cboDepartment.ListIndex) And _
    158.                      .Fields("CenterID").Value = cboCenter.ItemData(cboCenter.ListIndex) Then
    159.                      'Do nothing
    160.                   ElseIf .Fields("DeptID").Value = cboDepartment.ItemData(cboDepartment.ListIndex) Then
    161.                      'Do nothing
    162.                   Else
    163.                      'Change save new department value to DB
    164.                      adoRecordset!DeptID = cboDepartment.ItemData(cboDepartment.ListIndex)
    165.                   End If
    166.          
    167.                   If .Fields("CenterID").Value = cboCenter.ItemData(cboCenter.ListIndex) Then
    168.                      'Do nothing
    169.                   Else
    170.                      'Change save new department value to DB
    171.                      adoRecordset!CenterID = cboCenter.ItemData(cboCenter.ListIndex)
    172.                   End If
    173.                  
    174.                 .Update
    175.                
    176.                 Exit For

  2. #2

    Thread Starter
    Lively Member
    Join Date
    Apr 2004
    Location
    Alabama
    Posts
    126

    Re: Beginner Needing Suggestions

    VB Code:
    1. 'Looks for last record before EOF and allows new, yet duplicated employee info to be entered into the DB
    2.                ElseIf x = .RecordCount - 1 Then
    3.                     gbDuplicatedBadge = True
    4.                     boolSaveToDB = True
    5.                End If
    6.                .MoveNext
    7.             Next
    8.         Else
    9.             gbDuplicatedBadge = False
    10.             boolSaveToDB = False
    11.             txtBadge.SetFocus
    12.            
    13.             'Close recordset and connection
    14.             adoRecordset.Close
    15.             Set adoRecordset = Nothing
    16.             adoConnection.Close
    17.             Set adoConnection = Nothing
    18.            
    19.             SearchEmployeeDatabase = vbCancel
    20.             Exit Function
    21.         End If
    22.    
    23.    ElseIf .RecordCount = 0 Then
    24.           'Assigns zeros values since above fields are null
    25.           gPatSafetyGoals.Score = 0
    26.           gEnvironmentCare.Score = 0
    27.           gInfectionControl.Score = 0
    28.           gHumanResource.Score = 0
    29.           gPI_Process.Score = 0
    30.           gOSHA.Score = 0
    31.           gConfidentiality.Score = 0
    32.           gHIPAA.Score = 0
    33.           gCompliance.Score = 0
    34.           gJCAHO.Score = 0
    35.          
    36.           boolSaveToDB = True
    37.    End If
    38.  
    39.  'Insert Employee if no record of employee is found
    40.  If boolSaveToDB Then
    41.     .AddNew
    42.     .Fields("FName").Value = sFirstName
    43.     .Fields("LName").Value = sLastName
    44.     .Fields("BadgeNumber").Value = sBadge
    45.     .Fields("DeptID").Value = cboDepartment.ItemData(cboDepartment.ListIndex)
    46.     .Fields("CenterID").Value = cboCenter.ItemData(cboCenter.ListIndex)
    47.     .Update
    48.      'Debug.Print adoRecordset!fname
    49.  End If
    50.     .Close
    51. End With
    52.  
    53.   Set adoRecordset = Nothing
    54.  
    55.   adoConnection.Close
    56.   Set adoConnection = Nothing
    57.  
    58.   SearchEmployeeDatabase = vbYes
    59.  
    60. Else
    61.    'Informs user that connection failed and uses alternative to save employee data
    62.    MsgBox "This application could not establish a connection. Please ask your office manager to contact the PI Department."
    63.    adoConnection.Close
    64.    Set adoConnection = Nothing
    65.  
    66.    gsSaveEmpInfoToFile = vbYes
    67. End If
    68. Exit Function
    69.  
    70. AdoErrors:
    71. 'Errorhandling Declarations
    72. Dim errCollection As ADODB.Errors       'ADO Errors Object
    73.  
    74. 'In case the adoConnection is not established or there were other initiation problems
    75. On Error Resume Next
    76. SearchEmployeeDatabase = vbNo  'This may need to be changed if the error is not a DB error.
    77.  
    78. Set errCollection = adoConnection.Errors
    79.  
    80. ErrorLog errCollection
    81. End Function

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Beginner Needing Suggestions

    I haven't been thorough, but here's some advice on what I've looked at:

    1) The return type of the function is an Integer, yet you return values like vbCancel and vbNo; I would recommend usingthe appropriate enum if you can (in this case possibly vbMsgBoxConstants), as it makes working with the return values easier from the calling code.

    2) You have a little inconsistency in your style of referencing fields, sometimes you use .Fields("LName").Value and others you use adoRecordset!lname . I would recommend always using the first method as it is easier to read, and I think it works slightly faster. It also doesn't get binding errors, which I think the ! notation can.

    3) There's no need to store the result of a message box, you can use it directly in the If statement (or a Select Case if there are 3 buttons), eg:
    VB Code:
    1. If MsgBox("This badge number is already in use. Has your last name changed?", vbQuestion + vbYesNo, "Duplicated Badge Numbers") = vbNo Then
    2.             If MsgBox("Someone is already using this badge number. Would you like to make corrections?", vbExclamation + vbYesNo, "Duplicated Badge Numbers") = vbNo Then
    I prefer to split each parameter on to a separate line to make it easier to read, eg:
    VB Code:
    1. If MsgBox("This badge number is already in use. Has your last name changed?" _
    2.                   , vbQuestion + vbYesNo _
    3.                   , "Duplicated Badge Numbers")  _
    4.                   = vbNo Then
    5.             If MsgBox("Someone is already using this badge number. Would you like to make corrections?" _
    6.                     , vbExclamation + vbYesNo _
    7.                     , "Duplicated Badge Numbers")  _
    8.                     = vbNo Then

    4) Near the start of the function you check that the connection is open (good stuff), however you need to scroll to the end of the function to read the 'not connected' code (which is a long way!). It would be easier to read the function if you swapped the If around, so instead of:
    VB Code:
    1. 'Verifies database connection
    2. If adoConnection.State = adStateOpen Then
    3.  
    4.  '(lots of code)
    5.  
    6. Else
    7.    'Informs user that connection failed and uses alternative to save employee data
    8.    MsgBox "This application could not establish a connection. Please ask your office manager to contact the PI Department."
    9.    adoConnection.Close
    10.    Set adoConnection = Nothing
    11.  
    12.    gsSaveEmpInfoToFile = vbYes
    13. End If
    you could have:
    VB Code:
    1. 'Verifies database connection
    2. If adoConnection.State <> adStateOpen Then
    3.    'Informs user that connection failed and uses alternative to save employee data
    4.    MsgBox "This application could not establish a connection. Please ask your office manager to contact the PI Department."
    5.    adoConnection.Close
    6.    Set adoConnection = Nothing
    7.  
    8.    gsSaveEmpInfoToFile = vbYes
    9. Else
    10.  
    11.  '(lots of code)
    12.  
    13. End If


    In general your code looks good

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Apr 2004
    Location
    Alabama
    Posts
    126

    Re: Beginner Needing Suggestions

    Thanks man! and that from a Moderator! I was afraid i would get: "This is totally crap! Start over!"

    I was actually very much afraid. You helped my confidence level.

    I will use your suggestions! I might have mixed ADO syntax because i was just learning at the time and was trying to remember how to use both.
    Last edited by maurices5000; May 12th, 2005 at 03:37 PM.

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Apr 2004
    Location
    Alabama
    Posts
    126

    Re: Beginner Needing Suggestions

    Based on what you said above, my only question was about the Function type. You stated that my return type was integer but i returned values such as vbCancel. Well i thought that was an integer. :-)

    So can i create a Public Function FunctionName (...) As vbMsgBoxConstants?

    Maybe i misunderstood because that looks funny.

    I've also heard that it is best to use the Insert statements instead of ADO. If that is true, should worry about changing all my code or just leave it the same?

    Thanks!

  6. #6
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Beginner Needing Suggestions

    Thanks man! and that from a Moderator! I was afraid i would get: "This is totally crap! Start over!"
    well... I didn't wanna say it, but... naa, you're definitely on the right track

    You stated that my return type was integer but i returned values such as vbCancel. Well i thought that was an integer. :-)
    Technically yes, but only a few specific values, rather than the entire range of an Integer.

    If you return an enum then the values of the enum (like vbYes etc) will be listed when you type [i]FunctionName(parameters) =[i] in the calling code. In this situation you wont see much benefit, but if you use the function again later you will. Note that most/all of the VB built in functions return values like this when appropriate (and use them for the parameters).

    By the way, I was wrong about the name of the Enum, it is actually VbMsgBoxResult rather than vbMsgBoxConstants.

    I've also heard that it is best to use the Insert statements instead of ADO. If that is true, should worry about changing all my code or just leave it the same?
    It's debatable whether an Insert is better than using a recordset. For a single record there aren't any particularly significant reasons to use one or the other (for copying lots of data from one table to another, an Insert is definitely better).
    Last edited by si_the_geek; May 13th, 2005 at 01:38 PM. Reason: I used the wrong tags!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width