2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Accessで必ず使うVBA 全テーブル、クエリ、レポート、フォームを無変更で閉じる

Last updated at Posted at 2017-03-23
AllObjectClose.BAS
Sub AllObjectClose() 
'QiiQ From Qiita
'This Macro To Close Opened Tabels Queries Reports Forms on Current Database.
Dim db As dao.Database: Set db = CurrentDb
Dim rs As dao.Recordset
Dim tdf As dao.TableDef
Dim fld As dao.Field
Dim rpt As Access.Report, objForm As Access.Form
Dim myNo As Long
Dim fldName As String
Dim Qtb As dao.QueryDef
Dim i As Long, i1 As Long
If MsgBox("開いているTable,Query,Report,Formを無変更で閉じます(acSaveNo)。キャンセルで中止します", vbOKCancel + vbCritical, "確認") = vbCancel Then Exit Sub

For Each rpt In Application.CurrentProject.AllReports
If SysCmd(acSysCmdGetObjectState, acReport, rpt.Name) <> 0 Then
DoCmd.Close acReport, rpt.Name, acSaveNo
End If
Next

For Each objForm In Application.CurrentProject.AllForms
If SysCmd(acSysCmdGetObjectState, acForm, objForm.Name) <> 0 Then
DoCmd.Close acForm, objForm.Name, acSaveNo
End If
Next

For Each Qtb In db.QueryDefs 'Opend Query Close NoSave
If SysCmd(acSysCmdGetObjectState, acQuery, Qtb.Name) <> 0 Then
DoCmd.Close acQuery, Qtb.Name, acSaveNo
End If
Next

For Each tdf In Application.CurrentDb.TableDefs 'Opend Table Close NoSave
If SysCmd(acSysCmdGetObjectState, acTable, tdf.Name) <> 0 Then
DoCmd.Close acTable, tdf.Name, acSaveNo
End If
Next

End Sub

使用方法

このマクロはかなりAccessで使います。というのも今開いているテーブルを閉じないとエラーになったりするからです。
ACCESSのVBAの冒頭では必ずこのマクロを噛ませます。
つまり Call AllObjectClose
を書くのです。
このようにすることで、そのあと、安全にマクロを動かすことができます。
なお、変更があっても変更は無視して閉じます。つまり変更は反映されません。

それにしても変数とFor Eachは

Dim rpt As Access.Report, objForm As Access.Form

この変数の宣言のしかた、

For Each rpt In Application.CurrentProject.AllReports
For Each objForm In Application.CurrentProject.AllForms
この For Eachの指定の仕方はおもいつかないですね。Allがつくなんて。

閉じる順番は迷っています

とりあえずレポート、フォーム、クエリ、テーブルの順で閉じています。テーブルの無変更終了は他のオブジェクトに影響を与える可能性があるため一番最後でしょう。

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?