1 all powder board and ski microsoft access workbook chapter 7: integrity and transactions jerry...

48
1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

Upload: trinity-hicks

Post on 26-Mar-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

1

All Powder Board and Ski

Microsoft Access WorkbookChapter 7: Integrity and TransactionsJerry PostCopyright © 2007

Page 2: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

2

Compute Sales Tax

Sales Tax

From Figure 6.17

Page 3: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

3

Action

ActionCreate a new moduleAt the top add: Option ExplicitAdd the function ComputeSalesTaxUse Debug/Compile to find errorsClose the module

Page 4: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

4

Create Access Code Module

New Module

Visual Basic Editor

Application code

Page 5: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

5

Action

ActionEdit the Sale form in Design viewRight click the SalesTax box and select the Build Code optionSelect the Enter eventAdd the line: SalesTax = ComputeSalesTax(Subtotal)Run the formClick on the SalesTax box to test the calculation

Page 6: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

6

Add Event Code to the Sales Form

Right click and Build Code

Choose the Enter event

Call the new function

Page 7: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

7

Debugging

Set a break point

Use F8 to step through the code

Roll the cursor over a variable to see its current value

Page 8: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

8

Action

ActionOpen the SaleItem subform in Design viewOpen the form properties and modify the Record Source query to add the QuantityOnHand columnView the Field List boxDrag QuantityOnHand onto the formRun the form and improve the layout

Page 9: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

9

Adding QuantityOnHand to Subform

Right click to set properties

Build query to add QuantityOnHand

Drag QOH from Field List box onto form

Page 10: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

10

Form Events

1) Open 2) Load 3) Resize 4) Activate 5) Current

1233b

a

d

6) Enter

1233b

a

d

7) GotFocus

1233b

a

d

5) Close 4) Deactivate 3) Unload 2) LostFocus

1233b

a

d

1) Exit

1233b

a

d

ControlsForms

Change rows Close a Form

Open a Form

Page 11: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

11

Main Control Events

32

32

131

131

131

131

Enter

GotFocus

Change: keystrokes

Exit

BeforeUpdate

AfterUpdate

time

control event

131 LostFocus

Page 12: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

12

Action

ActionEdit the SaleItem subform in Design viewRight click the QOH box and build codeSelect the AfterUpdate eventAdd code to refresh the row and subtract QuantitySold from QuantityOnHandTest the form

Page 13: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

13

First Attempt: QOH Code

Private Sub QuantitySold_AfterUpdate() Me.Refresh ‘ Save data for new rows QuantityOnHand = QuantityOnHand - QuantitySoldEnd Sub

Page 14: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

14

Problems

What if the clerk entered the wrong value and should have entered 1 instead of 2 units?

Test it, and the code subtracts 1 from the QOH, leaving 7.

You need to add the original 2 units back.

QuantityOnHand = QuantityOnHand – QuantitySold + OldQuantity

Page 15: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

15

Clerk Changes SKU

950049 10

950050 10

Enter SKU 950049, Quantity 2 8

Inventory SKU QOH

Change SKU to 950050

Subtract

8

10

Add back to 950049

Subtract for 950050

Page 16: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

16

Clerk Changes SKU: Events

Clerk enters original SKU (950049) and Quantity

Code subtracts QuantitySold from QuantityOnHand (10 - 2 = 8)

Clerk changes SKU to new value (950050)

Active row becomes set for new value

Need to subtract QuantitySold from QuantityOnHand for 950050

Need to add QuantitySold back into QuantityOnHand for 950049

Private Sub cboSKU_Enter() If IsNull(cboSKU.Value) Then OldSKU = "-1" Else OldSKU = cboSKU.Value End IfEnd Sub

Page 17: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

17

Action

ActionOpen the SaleItem subform in Design viewChoose View/CodeAdd and modify the code as specified to handle changes in quantityTest the form

Page 18: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

18

SKU Changes: CodePrivate Sub cboSKU_Enter() If IsNull(cboSKU.Value) Then OldSKU = "-1" Else OldSKU = cboSKU.Value End IfEnd SubPrivate Sub cboSKU_AfterUpdate() If OldSKU <> "-1" And Not IsNull(QuantitySold) Then QuantityOnHand = QuantityOnHand - QuantitySold Dim sql As String sql = "UPDATE Inventory SET QuantityOnHand = QuantityOnHand + " _ & QuantitySold & " WHERE SKU='" & OldSKU & "'" Dim cmd As ADODB.Command Set cmd = CreateObject("ADODB.Command") cmd.ActiveConnection = CurrentProject.Connection cmd.CommandText = sql cmd.Execute End IfEnd Sub

Page 19: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

19

Delete CodeDim DelQuantity() As StringDim DelSKU() As StringDim nDel As IntegerPrivate Sub Form_Delete(Cancel As Integer) If IsNull(cboSKU.Value) Or IsNull(QuantitySold) Then Exit Sub If (nDel = 0) Then ReDim DelQuantity(Me.CurrentView) ReDim DelSKU(Me.CurrentView) End If DelSKU(nDel) = cboSKU.Value DelQuantity(nDel) = QuantitySold nDel = nDel + 1End SubPrivate Sub Form_AfterDelConfirm(Status As Integer) Dim i As Integer For i = 0 To nDel - 1 DeleteOneRow DelSKU(i), DelQuantity(i) Next i nDel = 0End Sub

Page 20: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

20

Delete Code 2

Private Sub DeleteOneRow(ByVal SKU As String, ByVal Qty As String) Dim sql As String sql = "UPDATE Inventory SET QuantityOnHand = QuantityOnHand + " _ & Qty & " WHERE SKU='" & SKU & "'" Dim cmd As ADODB.Command Set cmd = CreateObject("ADODB.Command") cmd.ActiveConnection = CurrentProject.Connection cmd.CommandText = sql cmd.ExecuteEnd Sub

Page 21: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

21

Action

ActionOpen the SaleItem subform in Design viewAdd the oldSKU variableAdd the SKU event code as describedPlace a breakpoint in the code before the Execute lineTest the form by changing an SKU numberExamine the sql line before it runsAdd the delete code as shownTest multiple changes to validate the code

Page 22: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

22

Transactions for Discounts

New table

Page 23: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

23

Rental Form

Button to open discount form

Page 24: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

24

Action

ActionCreate the Rental Discount form in Design viewAdd the text boxes and buttonSave the formOpen the Rental form in Design viewAdd a button to open the Discount formModify the open code as indicatedRun the form and test the button

Page 25: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

25

Rental Discount Form

RentID and Amount are filled in by code on the Rental form

Date default value is set to =Now() This is an unbound form built from

design view with no Record Source

Page 26: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

26

Action

ActionOpen the Rental Discount form in Design viewAdd the specified code to the button click eventTest the forms

Page 27: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

27

Rental Form Code: Discount Button

Private Sub cmdDiscount_Click()On Error GoTo Err_cmdDiscount_Click Dim stDocName As String Dim stLinkCriteria As String

stDocName = "GiveRentDiscount" DoCmd.OpenForm stDocName, , , stLinkCriteria Forms!GiveRentDiscount!txtRentID = RentID Forms!GiveRentDiscount!txtDiscountAmount = SubTotalCharges

Exit_cmdDiscount_Click: Exit Sub

Err_cmdDiscount_Click: MsgBox Err.Description Resume Exit_cmdDiscount_ClickEnd Sub

Page 28: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

28

Discount Code

Private Sub cmdDiscount_Click() Dim cmd As ADODB.Command Dim SQL1 As String, SQL2 As String Set cmd = CreateObject("ADODB.Command") cmd.ActiveConnection = CurrentProject.Connection SQL1 = "UPDATE RentItem SET RepairCharges=0 WHERE RentID=" & txtRentID SQL2 = "INSERT INTO RentalDiscount (RentID, DiscountDate, DiscountAmount, Reason)" & _ " VALUES (" & txtRentID & _ ", #" & txtDiscountDate & "#" & _ ", " & txtDiscountAmount & _ ", '" & txtReason & "')"

Page 29: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

29

Discount Code Continued

On Error GoTo Err_DiscountTrans cmd.ActiveConnection.BeginTrans cmd.CommandText = SQL1 cmd.Execute cmd.CommandText = SQL2 cmd.Execute cmd.ActiveConnection.CommitTrans lblMessage.Caption = "Changes recorded."

Exit1: Exit Sub

Err_DiscountTrans: cmd.ActiveConnection.RollbackTrans lblMessage.Caption = Err.Description Resume Exit1End Sub

Page 30: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

30

Action

ActionCreate a new query in Design viewTables: Sale and SaleItemCreate column SaleWeek: Val(Format([SaleDate],”ww”))Create column Value: [QuantitySold]*[SalePrice])Sum the Value column

Page 31: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

31

Query for Cursor: Weekly Sales

Val(Format([SaleDate],”ww”))

Page 32: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

32

Action

ActionCreate a new form in Design viewAdd a button Add a text box named txtAverageAdd the specified code to the buttonRun the form and test the codePlace a breakpoint and step through the code as it runs

Page 33: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

33

Form to Compute Average Increase

Page 34: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

34

Code to Compute Average Increase

Dim rst As ADODB.Recordset Set rst = CreateObject("ADODB.Recordset") Dim SQL As String SQL = "SELECT SaleWeek, [Value] FROM qryWeeklySales" rst.Open SQL, CurrentProject.Connection, adOpenStatic, adLockReadOnly Dim avg1 As Double, n As Integer Dim prior As Currency prior = -1 Do Until rst.EOF If (prior > 0) Then avg1 = avg1 + (rst("Value") - prior) / prior n = n + 1 End If prior = rst("Value") rst.MoveNext Loop rst.Close Me.txtAverage = avg1 / n

Open the SQL statement or table

Skip the first week because there is no prior value

Compute the percent change and keep a running total

Save the current value and move to the next row

Page 35: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

35

Keys: Create Sales and Items (barcode)

Customer ID card is scanned

Create new sale

Scan an item

Save sale item, update QOH and totals

Repeat until done (payment key)

Get SaleID

Save SaleID, SKU, Quantity

Page 36: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

36

Action

ActionCreate a new form in Design viewAdd boxes for CustomerID, EmployeeID, SKU, and

txtSaleID as the generated keyCreate a command button and add the indicated codeTest the formPlace a breakpoint at the top of the code and step

through the code

Page 37: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

37

Generate Sale Form

IDs and SKU would be scanned, but to test code, set default values

Page 38: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

38

Generate Sale Code-1

Dim sqlSale As String, sqlItem As String, sqlSaleItem As String Dim rstSale As ADODB.Recordset, rstModel As ADODB.Recordset Dim rstSaleItem As ADODB.Recordset Set rstSale = CreateObject("ADODB.Recordset") Set rstModel = CreateObject("ADODB.Recordset") Set rstSaleItem = CreateObject("ADODB.Recordset") sqlSale = "SELECT SaleID, CustomerID, EmployeeID, SaleDate FROM Sale" sqlItem = "SELECT ModelID, ListPrice FROM Inventory INNER JOIN “ & _

“ItemModel ON Inventory.ModelID = ItemModel.ModelID “ & _“WHERE SKU='" & SKU & "'"

sqlSaleItem = "SELECT SaleID, SKU, SalePrice, QuantitySold FROM SaleItem"

Dim cnn As ADODB.Connection Set cnn = CurrentProject.Connection

Page 39: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

39

Generate Sale Code-2

' Get the List Price for the SKU rstModel.Open sqlmodel, cnn, adOpenStatic, adLockReadOnly Dim ListPrice As Currency ListPrice = rstModel("ListPrice") rstModel.Close

' Open the Sale table and create a new sale rstSale.Open sqlSale, cnn, adOpenDynamic, adLockOptimistic Dim SaleID As Long rstSale.AddNew rstSale("SaleDate") = Now rstSale("CustomerID") = CustomerID rstSale("EmployeeID") = EmployeeID SaleID = rstSale("SaleID") rstSale.Update rstSale.Close

Page 40: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

40

Generate Sale Code-3

' Add the SKU to the SaleItem table using the new SaleID rstSaleItem.Open sqlSaleItem, cnn, adOpenDynamic, adLockOptimistic rstSaleItem("SaleID") = SaleID rstSaleItem("SKU") = SKU rstSaleItem("SalePrice") = ListPrice rstSaleItem("QuantitySold") = 1 rstSaleItem.Update rstSaleItem.Close

txtSaleID = SaleID

Page 41: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

41

Action

ActionCreate a new form in Design viewAdd a combo box to select customersAdd a text box to enter a new ZIP CodeCreate a button and add the indicated code for itTest the form

Page 42: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

42

Lock Test Form

Combo box to select customer

Page 43: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

43

Action

ActionCreate a CustomerLocks form as a datasheet into the

Customer tableRun the formEdit a ZIP Code but do not leave the cellSwitch to the new form and run it for the same CustomerIDReturn to the table and press the Tab key

Page 44: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

44

CustomerLock Test Form

Page 45: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

45

Optimistic Lock on the Form

Change the ZIP but do not leave the cell

Select the first customer, enter a ZIP code and change it

Switch back here and Tab out of the cell

Error message that value was changed

Page 46: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

46

Action

ActionSwitch to design view on the change form and add

the specified error-handling codeOpen the CustomerLocks form in Design view and

set the Record Locks property to Edited RecordRun both formsChange a ZIP Code in CustomerLocksEnter a new ZIP Code in the change form for the

same customer

Page 47: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

47

Pessimistic Lock on Forms

Change the ZIP but do not leave the cell

Select the first customer, enter a ZIP code and change it

The change is not made and the error is trapped because the row is locked

Page 48: 1 All Powder Board and Ski Microsoft Access Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2007

48

Handle Optimistic Locks in Code

RetryUpdate: rst.Open SQL, cnn, adOpenDynamic, adLockOptimistic rst("ZIP") = NewZIPCode rst.Update rst.Close

Exit_cmdNewZipCode_Click: Exit Sub

Err_cmdNewZipCode_Click: If (MsgBox(Err.Description, vbRetryCancel) = vbCancel) Then Resume Exit_cmdNewZipCode_Click End If rst.Cancel rst.Requery Resume RetryUpdate