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?

More than 1 year has passed since last update.

Accessのテーブルカラム名を動的に変更する

Posted at

はじめに

Accessのテーブルカラム名を動的に変更する方法について説明します。今回は、DAO(Data Access Objects)を使用してすべてのカラム名の最後ににアンダーバーを追加します。

ソース全体像

  1. AccessからVisual Basic Editorを開きます。
  2. 新しいモジュールを作成し、その中に以下のVBAコードを記述します。
Sub ChangeColumnNames()
    Dim db As DAO.Database
    Dim tbl As DAO.TableDef
    Dim fld As DAO.Field
    Dim newFieldName As String
    
    ' データベースオブジェクトを開く
    Set db = CurrentDb
    
    ' 指定したテーブル名を取得
    Set tbl = db.TableDefs("table_name")
    
    ' フィールドごとに処理
    For Each fld In tbl.Fields
        ' 新しいフィールド名を作成
        newFieldName = fld.Name & "_"
        
        ' カラム名を変更
        tbl.Fields(fld.Name).Name = newFieldName
    Next fld
    
    ' データベースオブジェクトを閉じる
    db.Close
    
    Set fld = Nothing
    Set tbl = Nothing
    Set db = Nothing
    
    MsgBox "すべてのカラム名の後ろにアンダースコアが追加されました。", vbInformation
End Sub

解説

はい、もっと見やすくするために、コードを細分化して説明します。

  1. テーブル名を指定する
Dim tbl As DAO.TableDef
Set tbl = CurrentDb.TableDefs("table_name")
  1. テーブルのカラム名を変更する
Dim fld As DAO.Field
For Each fld In tbl.Fields
    Dim newFieldName As String
    newFieldName = fld.Name & "_"
    tbl.Fields(fld.Name).Name = newFieldName
Next
  1. カラム名の変更を反映する
tbl.RefreshLink
  1. オブジェクトを解放する
Set fld = Nothing
Set tbl = Nothing

このマクロを実行すると、指定したテーブルのすべてのカラム名の後ろにアンダースコアが追加されます。

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?