0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excel VBAからAccess VBAを動かす

0
Last updated at Posted at 2025-12-28

はじめに

Excel VBAからAccess VBAのプロシージャを実行するコードを紹介します。

1. Accessツールの作成

標準モジュールに処理内容を記載します。

戻り値を返す場合はFunctionプロシージャを使用し、
戻り値を返さない場合はSubプロシージャを使用します。

AccessTool.accdb
Sub SampleCode(ByVal parameter1 As String, ByVal parameter2 As String)
    Debug.Print parameter1
    Debug.Print parameter2
End Sub

2. Excelツールの作成

標準モジュールにAccessツールの起動処理・実行処理・終了処理を作成します。

ExcelTool.xlsm
Sub ExecuteCode()
    
    'Accessのインスタンス変数
    Dim acApp As Object
    
    'Accessツールのファイルパスの変数
    Dim toolPath As String
    
    'Accessツールのファイルパスを作成
    toolPath = ThisWorkbook.Path & "\AccessTool.accdb"

    'Accessのインスタンスを作成
    Set acApp = CreateObject("Access.Application")
    
    'Accessツールを起動
    acApp.OpenCurrentDatabase toolPath
    
    'Accessツールを最大化
    acApp.RunCommand 10 'Application.RunCommand acCmdAppMaximize
    
    'Accessオブジェクトを表示
    acApp.Visible = True

    'acApp.Run プロジェクト名.プロシージャ名, 引数1,引数2
    acApp.Run "Database.SampleCode", "parameter1", "parameter2"
    
    'Accessを終了
    acApp.Quit
  
    'Accessのインスタンスを破棄
    Set acApp = Nothing
    
End Sub

AccessのApplication.Run メソッド

Runメソッドは以下のように記載します。(Microsoftの技術資料 参照)

'戻り値が無い場合
Application.Run "プロジェクト名.プロシージャ名", Arg1, Arg2, Arg30

'戻り値がある場合
var = Application.Run("プロジェクト名.プロシージャ名", Arg1, Arg2, Arg30)

紹介したコードでは、AppllicationをacApp変数に置き換えています。

引数は最大で30個設定が可能です。

プロジェクト名は省略可能ですが、省略すると動作しない場合があります。

プロジェクト名はVBEの[ツール] > [プロパティ]から確認できます。
image.png

Accessのオプション設定

Accessのオプション設定を下記①②のいずれかの設定にします。

①オプション > トラストセンター > マクロの設定
image.png

②オプション > トラストセンター > マクロの設定
image.png

②の設定をした場合、端末ごとに下記操作を行い、AccessツールをWindowsの[信頼できる場所]に追加します。
(1) Accessツールを開く
(2) [コンテンツの有効化]をクリック
image.png

Accessのオプション設定が適切にされていない場合、実行時エラー '40351' が発生します。
image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?