Database Management Systems Chapter 7 Calculations and Data Manipulation Jerry Post Copyright © 1998 1 D A T A B A S E Database Programming Variables Computations Standard Functions Debug Output Input Conditions Loops Arrays Data on Forms Properties Events DoCmd: Internal Commands Data Transfer Across Forms Data Lookup Programming SQL Database access programming Functions & statements grouped by task 2 D A T A B A S E Programming Environment Create code Tables (1) In forms and reports (2) Within the query system (3) Hosted in external programs External Program (3) DBMS Queries (2) Forms & Reports If ( . . ) Then SELECT . . . Else . . . UPDATE . . . End If C++ if (. . .) { // embed SQL SELECT … } (1) If (Click) Then MsgBox . . . End If 3 D A T A B A S E Programming Appendix Windows Environment Before Windows Your code did all of the work. Programmer In complete control. Code ran from top to bottom. Monolithic Code Start here Do this routine If (. . .) Then print . . . End If Wait for input More routines End here With Windows Structure and interface are defined by Windows standards. Event-driven. Code is in small pieces that are called as needed, when some event occurs. Windows Form Event/Trigger On_Click MsgBox . . . On_Change UPDATE . . . 4 D A T A B A S E Data on Forms Simple assignment [control] = value value = [control] Naming conventions Is it a variable or a control? Full names Forms![myform]![ctlTax] Null values: IsNull([control]) Form 32.50 ctlTax Code Sub ComputeTax Total = … taxRate = ... [ctlTax] = taxRate*Total End Sub 5 D A T A B A S E Control Properties and Methods Set properties with code Examples Employee Visible/Invisible Locked/Unlocked Combo box RowSource Methods SetFocus Undo Requery Code examples [control].Visible = False [control].Locked = False [control].SetFocus [combo].RowSource= “SELECT ... FROM . . .” Sub Employee_AfterUpdate() If (Employee = “manager”) Then [cmdSalary].Visible = True [cmdSchedule].Visible = True Else [cmdSalary].Visible = False [cmdSchedule].Visible = False End If End Sub 6 D A T A B A S E Transfer Data Across Forms Full names: Forms! [formname1]! [control1] Forms must be open Form1.Visible = True Subforms: Forms! [formname1]! [subform].Form! [control1] 7 D A T A B A S E Common Properties Forms Record Source Caption Default View Menu/Scroll Bars Navigation/Selection Size/Center Pop Up/Modal/Border Controls Name Control Source Format/Decimal/Default Controls Input Mask Validation Rule/Text Status Bar Auto Tab/Enter Visible Enabled/Locked Tab Stop/Index Size, Position Back/Fore Color/Effects Border Font 8 D A T A B A S E Common Events Forms Current Before/After Insert Before/After Update Delete Before/After Del Confirm Open/Close Load/Unload Activate/Deactivate Got/Lost Focus Click/Double Click Error/Timer Controls Before/After Update Change Enter/Exit Got/Lost Focus Click Double Click Mouse Key Down/Up/Press 9 D A T A B A S E DoCmd: Internal Commands See help system Common uses FindNext FindRecord GoToControl GoToPage GoToRecord Hourglass Maximize/Minimize OpenForm OpenQuery OpenReport Print Quit RunApp (Shell) RunSQL SetWarnings TransferDatabase TransferSpreadsheet 10 D A T A B A S E Programming: SQL Select Into New table Insert Into Operate on sets of data Use String for Where Use DoCmd RunSQL Append rows Update Change data Delete Delete rows 11 D A T A B A S E Update Changes set of values--based on Where Syntax Update table SET col1=val1, col2=val3 Where condition Examples strSQL = “Update Order Set EstShipDate=OrderDate+3” DoCmd RunSQL strSQL strSQL = “Update Product Set Price = Price*” strSQL = strSQL & CStr(1.0 + [ctlIncrease]) strSQL = strSQL & “ Where “ & [ctlWhere] DoCmd RunSQL strSQL 12 D A T A B A S E SQL Example: Employee Titles Employee Table Change titles EID 2298 9983 2736 Create a form Old title (combo) New title Command button Name Adams Cuervo Dubai Phone 2253 9973 3385 Title Manager Supervisor Worker Manager Team Leader Go SQL UPDATE Employee SET Title = " Team Leader " WHERE Title = " Manager ”; 13 D A T A B A S E SQL Example: New Titles UPDATE Employee SET Title = "Team Leader" WHERE Title = "Manager"; Manager Team Leader Go Sub cmdGo_AfterUpdate Build Update command in a String, using values from OldTitle and NewTitle. Execute the command. End Sub 14 D A T A B A S E Build the SQL Update Command Sub cmdGo_AfterUpdate Dim strSQL As String strSQL = "UPDATE Employee SET Title = ” & txtNewTitle & " WHERE Title = ” & cboOldTitle _ End Sub strSQL: UPDATE Employee SET Title = Team Leader WHERE Title = Manager Problem: You need quotation marks around the titles. 15 D A T A B A S E SQL Update Example SQL Sample UPDATE Employee SET Title = "“Team Leader " WHERE Title = "Manager"; Sub cmdGo_AfterUpdate Dim strSQL As String, q as String q = Chr(34) ‘ quotation mark strSQL = "UPDATE Employee SET Title = " & q & [txtNewTitle] & q & " WHERE Title = " & q & [cboOldTitle] & q & " ; " DoCmd.SetWarnings False DoCmd.RunSQL strSQL DoCmd.SetWarnings True _ ‘ Turn off warnings ‘ Execute the SQL command End Sub 16 D A T A B A S E Debug your Query 17 D A T A B A S E Insert Into (1) Adds rows to a table Syntax Insert Into table (col1, col2, …) Values (value1, value2, … LastName FirstName Masi Jorge CID Last … 938 Sosa Masi First Phone Javier 8474 Jorge strSQL = “Insert Into [Customer] (Last, First)” strSQL = strSQL & “ Values (“ & “””” & [ctlLast] & “””” strSQL = strSQL & “,” & “””” & [ctlFirst] & “””” & “)” DoCmd RunSQL strSQL 18 D A T A B A S E Insert Into (2) Copies data rows to a second table Syntax INSERT INTO {new table, columns} SELECT {any SQL} Example, move all customers who have not placed orders recently. Let users define “recently” by picking the number of days. SQL INSERT INTO OldCustomer SELECT * FROM Customer WHERE CustomerID NOT IN (SELECT CustomerID FROM Order WHERE (Odate > Date() - x); 19 D A T A B A S E Code Example for Insert CustomerID 7763 3635 4456 O# 9987 2275 Name Phone Juarez 9987 Kramer 2285 Ciaro 8474 C# 3635 4456 Odate 02-15-98 05-23-98 CustomerID Name Phone 7763 Juarez 9987 … Customers who have not placed an order within some time frame. Dim strSQL strSQL = “INSERT INTO OldCustomer” strSQL = strSQL & “ SELECT * FROM Customer WHERE” strSQL = strSQL & “ CustomerID NOT IN” strSQL = strSQL & “ (SELECT CustomerID FROM Order” strSQL = strSQL & “ WHERE (Odate > Date() - “ strSQL = strSQL & [txtDays] & “);” Time frame (txtDays) DoCmd.RunSQL strSQL is given by user. 20 D A T A B A S E Delete Delete a set of rows that match a condition Syntax: Delete From table Where condition Cascade on Delete! Example: Move old customer data strWhere = “CustomerID NOT IN (SELECT CustomerID FROM Order” strWhere = strWhere & “ WHERE (Odate > Date() - “ & [txtDays] & “);” strSQL = “INSERT INTO OldCustomer” strSQL = strSQL & “ SELECT * FROM Customer WHERE “ & strWhere DoCmd.RunSQL strSQL ‘ Copy old customer data ‘ To Do: Backup the data in related tables strSQL = “DELETE FROM Customer WHERE “ & strWhere DoCmd.RunSQL strSQL ‘ Delete from main table & cascade 21 D A T A B A S E Data Lookup Commands: D... Syntax D... (expr, domain, criteria) “Column” “Table” “Where Clause” Functions DAvg, DCount, DFirst, DLast, DMin, DMax, DStDev, DStDevP, DSum, DVar, DVarP Dlookup Column Table V = DSum(“BalanceDue”, “Customer”, “City=‘Chicago’”) Where Clause Usually better to use SQL. Or to write DAO code. 22 D A T A B A S E Data Access Object Programming Purpose Track through table or query one row at a time. Data cursor/pointer to active row. Why? Performance. SQL cannot do everything. Complex calculations. Compare multiple rows. Year 1995 1995 1996 1997 1998 Sales 104,321 104,321 145,998 276,004 362,736 MoveNext MovePrevious MoveFirst MoveLast Move Test for Beginning and End of File 23 D A T A B A S E Data Access Object Programming Containers DBEngine Workspaces Databases Recordsets Read Write DBEngine Workspace Database Recordset (query) Dim dbs As Database Dim rst As Recordset Set dbs = CurrentDB() Set rst = dbs.OpenRecordset(“my query”) 24 D A T A B A S E Program Structure Set dbs = CurrentDB() Choose the database strSQL = “SELECT … “ Define the query Set rst = dbs.OpenRecordset(strSQL) Open the query to the first row Do Until (rst.EOF) Read or Write data in the current row rst.MoveNext Loop rst.Close Loop through the query Read data or make changes Go to the next row Repeat Close the query 25 D A T A B A S E Problems with Multiple Users Original Data Modified Data Name Alice Carl Donna Ed Name Alice Neal Carl Donna Ed Sales 444,321 254,998 652,004 411,736 New row is added--while code is running. Sales 444,321 333,229 254,998 652,004 411,736 Set rst = dbs. OpenRecordset(“Data”) Value1 = rst!Sales ‘ Alice (444,321) rst.MoveNext ‘ Carl … rst.MovePrevious ‘ ??? Which row 26 D A T A B A S E Table Locator Commands Move Commands Bookmarks Dim MyMark As String MyMark = rst.Bookmark .MoveNext .MovePrevious .MoveFirst .MoveLast .Move nRows (Save position) .Move . . . (Move somewhere else) rst.Bookmark = MyMark Location tests BOF EOF Name Alice Neal Carl Donna Ed (Return to mark) Sales 444,321 333,229 254,998 652,004 411,736 Save position bmk = rst.Bookmark rst.MoveNext rst.Bookmark = bmk 27 D A T A B A S E Recordset Find Commands .FindFirst “condition” .FindLast “condition” .FindNext “condition” .FindPrevious “condition” Inefficient: Sequential search Use SQL instead rst.Index = “PrimaryKey” rs.NoMatch rs.Seek Indexed One item rst.Seek “=“, keyvalue If (rst.NoMatch = False) Then ‘ Make changes End If 28 D A T A B A S E Sample Data Access Code Dim dblSum As Double Dim dbs As Database Dim rst As Recordset Set dbs = CurrentDB() Set rst = dbs.OpenRecordset(“Customer”) dblSum = 0.0 Do Until (rst.EOF) dblSum = dblSum + rst!BalanceDue rst.MoveNext Loop rst.Close MsgBox “Total Due = “ & dblSum Compute total of BalanceDue. Normally use SQL instead. 29 D A T A B A S E Sample Code to Change Data Dim dbs As Database Dim rst As Recordset Do Until (rst.EOF) rst.Edit rst!BalanceDue = rst!BalanceDue*(1 + [PctIncrease] ) rst.Update rst.MoveNext Loop rst.Close Add a 10% charge to the BalanceDue for every customer. The 10% value is entered on the form by the user. What happens if the row is already locked? Normally use SQL instead. 30 D A T A B A S E Error Handling Errors are events Simple code: Event Options Display error and exit MsgBox Err.Description, , “Title” Resume Exit_Label On Error Goto [label] On Error Goto 0 On Error Resume Next Resume Options On Error Goto ErrSub1 Program code ExitSub1: Exit Sub Resume Resume Next Resume label Error occurs ErrSub1: MsgBox Err.Description,,”Errors” Resume ExitSub1 31 D A T A B A S E Alternate Error Handling Sub mySubroutine On Error Resume Next … Set rst=dbs.OpenRecordset(“data”) If IsNull(rst) Then … Handle the error End If Error occurs, skip to next line. Test for error, handle it. Exit Sub 32 D A T A B A S E Concurrent Access Concurrent Access Two processes Multiple users or processes changing the same data at the same time. Final data will be wrong! Force sequential Locking Delayed, batch updates Receive Payment 1) Read balance 2) Subtract pmt 4) Save new bal. 800 -200 600 Receive payment ($200) Place new order ($150) Initial balance $800 Result should be $800 200 + 150 = $750 Interference result is either $600 or $950 Customers ID Jones Balance $800 $600 $950 Place New Order 3) Read balance 5) Add order 6) Write balance 800 150 950 33 D A T A B A S E Deadlock Deadlock Two (or more) processes have placed locks on data and are waiting for the other’s data. 1) Lock Data A 3) Wait for Data B Many solutions Random wait time Global lock manager Two-phase commit - messages Data A Data B 2) Lock Data B 4) Wait for Data A 34 D A T A B A S E Lock Manager Resource A Process1 Process2 Resource B Lock Wait Process7 Resource E Lock Wait Lock Wait Process5 Process6 Resource D Wait Lock Process3 Process4 Resource C Wait Lock Wait Wait 35 D A T A B A S E Concurrent Access Customer Using & Adams locked Brown Jones Balance 152.35 315.81 115.67 Running the program to add interest charges generates an error message. Do until rst.EOF rst.Edit rst!Balance = rst!Balance*(1.0+rate) rst.Update rst.MoveNext Loop 36 D A T A B A S E Errors and Locks On Error Goto ErrSub1 … rst.Edit rst!Balance = rst!Balance*1.10 rst.Update … ExitSub1: Exit Sub If the table is locked, Edit will cause an error. ErrSub1: If ( MsgBox (Err.Description, VbRetryCancel, "Error (RS)” ) = vbRetry ) Then Resume Let the user retry the edit or exit. Else To do it automatically, wait Resume ExitSub1 for a random number of seconds. End If 37 D A T A B A S E Post’s Picky Programming • Use a naming convention. • Use proper indentation. • Comment your work. • Avoid spaces in variable names. • Use Option Explicit. • Recompile constantly. • Use as many parentheses as possible. • Split complex conditions. • Make it easy for the user. • Use the status bar and tool tips. • All code must be subject to error trapping. • Use Retry with rst.Edit sections. • Use subroutines and functions to simplify. • Keep backup copies. • Never use a raw number--use Const. • Remember that databases can be moved. • Test applications on different hardware. •Test all calculations by hand. 38 D A T A B A S E Comments dblSum = 0# Do While Not rst.EOF dblSum = dblSum + rst!Balance rst.MoveNext Loop Weak comments ' Initialize the accumulator ' Loop through the table ' Accumulate the balance ' Move to the next row ' End the loop ' Need to compute total balance from sales Useful comments ' Will use a loop instead of SQL ' Because some conditions will be added later dblSum = 0# Do While Not rst.EOF ' Add condition when user provides it, for example ' If this customer has more than three sales past due, ' only count the three most recent (write off the older ones) dblSum = dblSum + rst!Balance rst.MoveNext Loop 39 D A T A B A S E Sally’s Pet Store Main Switchboard Employee logs in. Buttons are presented based on the management level of the employee. Accounting Marketing Employees Not available to this employee. Purchasing forms are accessible by this employee. 40 D A T A B A S E Sally’s Pet Store: Switchboard Logic Event: EmployeeID AfterUpdate On Error Goto ErrEIDAU Declare variables. Lookup assigned ManagementLevel of employee. Get Management levels for each section. Make two sections of buttons invisible. If (MgtLevel > Level1) Then Make first section of buttons visible. If (MgtLevel > Level2) Then make second section of buttons visible. End If End If ExitEIDAU: Exit Sub ErrEIDAU: MsgBox Resume ExitEIDAU 41 D A T A B A S E Sally’s Pet Store: Switchboard Code Private Sub EmployeeID_AfterUpdate() On Error GoTo ErrEIDAU Dim varLevel, varMGTLEVEL1, varMGTLEVEL2 If Not IsNull(EmployeeID) Then varLevel = DLookup("EmployeeLevel", "Employee", _ "EmployeeID=" & [EmployeeID]) If Not IsNull(varLevel) Then varMGTLEVEL1 = DLookup("Value", "Preferences", _ "KeyID=" & """" & "MGTLEVEL1" & """") varMGTLEVEL2 = DLookup("Value", "Preferences", _ "KeyID=" & """" & "MGTLEVEL2" & """") End If End If cmdAnimalPurchase.Visible = False cmdMerchandisePurchase.Visible = False cmdInventory.Visible = False cmdAccounting.Visible = False cmdMarketing.Visible = False cmdEmployees.Visible = False 42 D A T A B A S E Sally’s Pet Store: Switchboard Code If (varLevel > Val(varMGTLEVEL1)) Then cmdAnimalPurchase.Visible = True cmdMerchandisePurchase.Visible = True cmdInventory.Visible = True If (varLevel > Val(varMGTLEVEL2)) Then cmdAccounting.Visible = True cmdMarketing.Visible = True cmdEmployees.Visible = True End If End If ExitEIDAU: Exit Sub ErrEIDAU: MsgBox Err.Description, , "Unexpected Error (EIDAU)" Resume ExitEIDAU End Sub 43 D A T A B A S E Sally’s Pet Store: Employees Enter a ZIP code and the form tries to find a matching city. Choose a city and the ZIP code is entered automatically. Spin buttons can be used to set employee level. 44 D A T A B A S E Sally’s Pet Store: Employee Spin Button Private Sub SpinLevel_SpinDown() If IsNull(EmployeeLevel) Then EmployeeLevel = 0 Else If (EmployeeLevel > 0) Then EmployeeLevel = EmployeeLevel - 1 End If End Sub Private Sub SpinLevel_SpinUp() If IsNull(EmployeeLevel) Then EmployeeLevel = 1 Else If (EmployeeLevel < 255) Then EmployeeLevel = EmployeeLevel + 1 End If End Sub 45 D A T A B A S E Sally’s Pet Store: City Private Sub CityID_AfterUpdate() On Error GoTo ErrCIDAU ‘ Requires a large city table. If IsNull([ZipCode]) Then [ZipCode] = DLookup("ZipCode", "City", "CityID=" & [CityID]) End If ‘ Do not replace an existing ZipCode entry. ExitCIDAU: Exit Sub ErrCIDAU: MsgBox Err.Description, , "Unexpected Error (CIDAU)" Resume ExitCIDAU End Sub 46 D A T A B A S E Sally’s Pet Store: ZipCode Private Sub Zipcode_AfterUpdate() On Error GoTo ErrZCAU Dim strZipShort As Variant, newCityID As Variant strZipShort = Get5DigitZipCode(ZipCode) newCityID = DLookup("CityID", "City", _ "ZipCode=" & """" & strZipShort & """") If Not IsNull(newCityID) Then [CityID] = newCityID End If ‘ City table only uses 5 digit codes. ExitZCAU: ‘ But we need to store 9 digits in ZipCode. Exit Sub ErrZCAU: MsgBox Err.Description, , "Unexpected Error (ZCAU)" Resume ExitZCAU End Sub 47 D A T A B A S E Programming Review: Variables Integer 2 bytes -32768 32767 Long 4 bytes +/- 2,147,483,648 Single 4 bytes +/- 3.402823 E 38 +/- 1.401298 E-45 Global, Const, Static Double 8 bytes +/- 1.79769313486232 E 308 +/- 4.94065645841247 E-324 Currency 8 bytes +/- 922,337,203,685,477.5808 String & String*n Variant Any data type Null 48 D A T A B A S E Programming: Scope and Lifetime Scope Where is the variable, and which procedures can access it? Lifetime When is the variable created, and when is it destroyed? Different procedures, different variables. Created and destroyed each time the button is clicked. Form Button1 Button2 Form--Module Code Sub Button1_Click() Dim i1 As Integer i1 = 3 End Sub Sub Button2_Click() Dim i1 As Integer i1 = 7 End Sub 49 D A T A B A S E Programming: Global Variables Wider scope and lifetime Created at a higher level Form Public module Accessible to any procedure in that form or module. Declare it Global to make it available to any procedure. Form Button1 Button2 Form--Module Code Dim i2 As Integer Sub Button1_Click() i2 = 20 End Sub Variable is created when form is opened. Sub Button2_Click() Clicking Button1 sets the i2 = i2 + 7 initial value. End Sub Clicking Button2 modifies the value. What if user clicks buttons in a different order? 50 D A T A B A S E Programming: Computations Standard Math + - * / \ Integer divide ^ Exponentiation (2^3 = 2*2*2 = 8) Mod (15 Mod 4 = 3) (12 + 3 = 15) “Frank” & “Rose” “FrankRose” Left(“Jackson”,5) “Jacks” Trim(“ Maria “) “Maria” String & Concatenation Left, Right, Mid Trim, LTrim, RTrim String Chr, Asc LCase, UCase InStr Len StrComp Format Len(“Ramanujan”) 9 String(5,”a”) “aaaaa” InStr(“8764 Main”,” “) 5 51 D A T A B A S E Programming: Standard Functions Numeric x = loge (ex) Exp, Log Trigonometric functions ? Atn, Cos, Sin, Tan =30 Sqr 92 2 = 1.414 Abs Abs(-35) 35 Sgn Sgn(-35) -1 Int, Fix Int(17.893) 17 Rnd, Randomize Rnd() 0.198474 52 D A T A B A S E Programming: Standard Functions: Date/Time Date, Now, Time DateAdd, DateDiff “y”, “m”, “q” . . . Firstweekday 1=Sunday,. . . Can also be used to find number of Fridays, between two dates. 02/19/99 today 03/21/99 DateDue DateDue = DateAdd(“d”, 30, Date()) 53 D A T A B A S E Programming: Standard Functions: Variant Variant IsDate IsNumeric VarType IsEmpty IsNull 54 D A T A B A S E Programming: Debug Stop Ctrl-Break F5: Go F8: Step through S-F8: Step over Breakpoints Immediate Window ? or Print Any assignment Any code 55 D A T A B A S E MsgBox Programming: Output: Message Box Message Type Title Types: Use Constants vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Defaults Icons vbCritical Stop sign vbQuestion Question mark vbExclamation Warning vbInformation Circle i Responses vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo vbDefaultButton1 vbDefaultButton2 vbDefaultButton3 MsgBox "This is a message box", vbYesNoCancel + vbInformation, "Sample Box" 56 D A T A B A S E InputBox Programming: Input: InputBox Prompt Title Default X-Pos, Y-Pos Prompt Cannot change box size Use Chr(10) & Chr(13) for blank lines. Returns text or Variant Cancel = zero string ““ Positions Twips Twentieth of inch point 72 points 1440 twips per inch Dim str As String str = InputBox( "Enter your name:", "Sample Input", , 5000, 5000) 57 D A T A B A S E Programming: Conditions If Conditions If (Condition) Then statements for true Else <, <=, >, >=, =, <> And, Or, Not, Xor Eqv, Imp (logic) statements for false End If IIF (Cond., True, False) Select Case (expr) Case value statements Case value2 Case Else End Select If (Condition1) Then statements for true Else statements for false If (Condition2) Then statements for true End If End If 58 D A T A B A S E Programming Select Example Message Box Could use repeated If statements Better to use Select Case response = MsgBox(…) If (response == vbYes) Then ‘ statements for Yes Else If (response == vbNo) Then ‘ statements for No Else ‘statements for Cancel End If End If response = MsgBox(…) Select Case response Case vbYes ‘ statements for Yes Case vbNo ‘ statements for No Case vbCancel ‘ statements for Cancel End Case 59 D A T A B A S E Programming: Loops Initialize value Statements Do For … Next For Each Change value Test condition Do Until (x > 10) Do While (x <= 10) ‘ Statements ‘ Statements x=x+1 x=x+1 Loop Loop Do For x = 1 to 10 ‘ Statements x=x+1 ‘ Statements Next x Loop Until (x > 10) 60 D A T A B A S E Programming: Loops Again Do For/Each (objects) Do {While | Until} Exit Do (optional) Loop For Each element In group [Exit For] (optional) Next element With (objects) Do Loop {While | Until} With object End With For/Next For counter = start To end Step increment Exit For (optional) Next counter 61 D A T A B A S E Programming Subroutines and Functions Sub name (var1 As . . ., var2, . . .) End Sub Function fname (var1 As . . .) As datatype fname = … ‘ returns a specific value End Function Variables are passed by reference Changes made to the parameters in the subroutine are passed back to the caller. Unless you use ByVal Changes are made to a copy of the parameter, but are not returned to the calling program. 62 D A T A B A S E Programming: Example Subroutine Main program … StatusMessage “Trying to connect.” … StatusMessage “Verifying access.” … End main program Sub StatusMessage (Msg As String) ‘ Display Msg, location, color End Sub 63 D A T A B A S E Programming: Parameter Types Main j=3 DoSum j … ‘ j is now equal to 8 Subroutine DoSum (j2 As Integer) j2 = 8 End Sub Main j=3 DoSum j … ‘ j is still equal to 3 Subroutine DoSum (ByVal j2 As Integer) j2 = 8 End Sub By Reference Changes to data in the subroutine are passed back. By Value Creates a copy of the variable, so changes are not returned. 64 D A T A B A S E Programming Arrays and User Types Arrays Dim array(sub, . . .) As type Dim iSorts(10) As Integer (lower To upper, . . .) ReDim [Preserve] array .. . Option Base 0 | 1 v 2.0 arrays less than 64KB Type Tname Specifying bounds: User defined types ename1 As type ename2 As type End Type Dim var1 As Tname var1.ename1 = . . . var1.ename2 = . . . 65 D A T A B A S E Programming: Financial Functions Fixed payments PV (rate, nper, pmt, fv, due) FV (rate, nper, pmt, pv, due) IPmt (rate, per, nper, pv, fv, due) NPer (rate, pmt, pv, fv, due) Pmt (rate, nper, pv, fv,due) PPmt (rate, per, nper, pv, fv, due) Rate (nper, pmt, pv, fv, due, guess) rate per nper pv fv due Arrays NPV (rate, array) IRR (array, guess) MIRR (array, finrate, re_rate) Depreciation DDB (cost, salv, life, period) SLN (cost, salvage, life) SYD (cost, salv., life, period) interest rate per period specific period number # of periods present value future value 0=due at end, 1=due at start 66 D A T A B A S E Programming: Text File Input/Output Open filename As # file# Close # file#, Reset Print #,Put, Write Spc, Tab Get, Input #, Line Input # EOF, LOF Seek # file#, position ChDir, ChDirve Dir Kill, (re)Name Lock, Unlock CurDir, MkDir, RmDir 67 D A T A B A S E DDE: Dynamic Data Exchange Shell DDEInitiate DDEExecute DDEPoke, DDE Send Application must be running Start a conversation/topic Issue a command Place data Send data DDE, DDERequest Get data Request data DDETerminate Close the session 68 D A T A B A S E OLE: Object Linking & Embedding CreateObject (class) “appname . objecttype” GetObject (file, class) Methods and syntax are defined by the software that exports the object. Example Dim obj As Object set obj = CreateObject(“Word.Basic”) obj.Bold obj.Insert “text” obj.SaveAs “file” 69