0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AccessのVBAでテーブル情報一覧を動的に取得(ローカルテーブル、リンクテーブル、システムテーブル)

Last updated at Posted at 2023-08-14

やり方

Dim def_ As DAO.TableDef

For Each def_ In CurrentDb.TableDefs
    
    '参考値としてテーブル名とAttributes値を出力。
    Debug.Print def_.Name
    Debug.Print def_.Attributes
    
    If (def_.Attributes And TableDefAttributeEnum.dbSystemObject) Then
        Debug.Print "システムテーブル"
    End If 
        
    'ローカルテーブルはTableDefAttributeEnumに該当する値が無いため、
    'Attributesの値を=で判定。
    If def_.Attributes = 0 Then
        Debug.Print "ローカルテーブル"
    End If
        
    If (def_.Attributes And TableDefAttributeEnum.dbAttachedODBC) Then
        Debug.Print "ODBC接続のリンクテーブル"
    End If
    
    If (def_.Attributes And TableDefAttributeEnum.dbAttachedTable) Then
        Debug.Print "ODBC接続ではないリンクテーブル"
    End If
    
    Debug.Print vbCrLf '出力が見やすいように改行挟む。
    
Next

下記のようなテーブルを持っているAccessの場合…
image.png

実行結果は下記。
image.png

なぜAndで判定?

テーブル種類の判定について、理解するのに少し時間かかったので自分なりに整理。

=で判定できない

TableDefAttributeEnum.dbAttachedODBC『536870912』 です。
image.png

ですが、前述のサンプルだと、ODBC接続リンクテーブルのAttributesは 『537001984』 となっています。

536870912 ≠ 537001984

なので、
If def_.Attributes = TableDefAttributeEnum.dbAttachedODBC Then
のように = で判定はできません。

じゃあAttributesに入っている値は何を表しているのか

Attributesの値『537001984』は『536870912 + 131072』と分割できます。

名前 説明
536870912 TableDefAttributeEnum.dbAttachedODBC リンクされた ODBC データベース テーブル。
131072 TableDefAttributeEnum.dbAttachSavePWD リンクされたリモート テーブルのユーザー ID とパスワードを保存します。

Attributesには『ODBCリンクテーブル』かつ『IDとパスワードを保存している』という2つの情報が入っています。

なのでAndで判定が必要。

参考サイトさん

バージョン

Microsoft Windows [Version 10.0.19045.3324]
Microsoft Access for Microsoft 365 MSO (バージョン 2307 ビルド 16.0.16626.20170) 32 ビット

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?