4章 カスタマイズ4-4レポート

印刷時に商品テーブルを更新する[Access97]


印刷時に商品テーブル等の他ファイルを更新することができます。


<操作手順>
  1. Soraレポートを[デザイン]で開く
  2. コード画面の表示
    [表示]ツールメニューの[コード]をクリックします。
  3. 商品テーブル更新
    [詳細]の[印刷時]イベントに下記内容を追加します。
    Private Sub 詳細_Print(Cancel As Integer, PrintCount As Integer)
        apRptPrint Me
        '商品テーブル更新(FindFirstの例)
        Dim rstShohin As Recordset   'レコードセットオブジェクト変数定義「H->」
        Set rstShohin = CurrentDb.OpenRecordset("商品", dbOpenDynaset)    '「ファイル指定」
        If Not IsNull(Me![商品番号1]) Then
            rstShohin.FindFirst "商品番号 = " & Me![商品番号1]      '「検索」
            If Not rstShohin.NoMatch Then   '検索OK
                '更新
                rstShohin.Edit              '更新編集開始
                If Not IsNull([数量1]) Then
                    rstShohin![在庫数] = rstShohin![在庫数] - Me![数量1]        '「更新」在庫数
                End If
                rstShohin.Update            '更新
            End If
        End If
        If Not IsNull(Me![商品番号2]) Then
            rstShohin.FindFirst "商品番号 = " & Me![商品番号2]      '「検索」
            If Not rstShohin.NoMatch Then   '検索OK
                '更新
                rstShohin.Edit              '更新編集開始
                If Not IsNull([数量2]) Then
                    rstShohin![在庫数] = rstShohin![在庫数] - Me![数量2]        '「更新」在庫数
                End If
                rstShohin.Update            '更新
            End If
        End If
        rstShohin.Close
        Set rstShohin = Nothing
    End Sub
    

商品テーブル更新のSQLバージョン
上記の商品テーブル更新をSQLで記述したものです。同様の処理内容です。
Private Sub 詳細_Print(Cancel As Integer, PrintCount As Integer)
    apRptPrint Me
    '商品テーブル更新(SQLの例)
    Dim db As Database
    Set db = CurrentDb()
    '更新
    Dim strSQL As String
    If Not IsNull(Me![商品番号1]) Then
        strSQL = "UPDATE 商品 SET 在庫数 = 在庫数 - " & Me![数量1] & " WHERE 商品番号 = " & Me![商品番号1] & ";"
        db.Execute strSQL  '実行
    End If
    If Not IsNull(Me![商品番号2]) Then
        strSQL = "UPDATE 商品 SET 在庫数 = 在庫数 - " & Me![数量2] & " WHERE 商品番号 = " & Me![商品番号2] & ";"
        db.Execute strSQL  '実行
    End If
    Set db = Nothing
End Sub

<参照>
  1. 書籍「Microsoft Access97 Visual Basic ステップバイステップ」
    Lesson13 Visual Basicでレポートをカスタマイズする(p383)