Excel アドインを VBA で作成する
このページでは、Excel アドインを VBA で作成する手順を記載します。
目次
注意
- 確認した Excel のバージョンは Excel for Office 365 (16.0.11727.20222。Excel 2019 相当) です。将来のバージョンでは動作しない可能性があります。
単純な手順 (クイックツールバーに追加する)
1. VBA で関数を作成する
VBA で関数を1つ作成します。(「マクロの記録」で関数を作っても可)


Sub Test()
MsgBox "Test"
End Sub
2. 1 を xlam ファイルで保存し、一度 Excel を再起動する
C:\Users\ユーザー名\AppData\Roaming\Microsoft\AddIns
に保存
※ Excel を再起動しないと 3 で項目が出てきません。
3. 「開発」タブ >「Excel アドイン」から 2 で保存したファイル名と同じものをチェック


4. 「クイックアクセスツールバーのユーザー設定」>「その他のコマンド」からコマンドの種類を「マクロ」にして 1 で作成したマクロを選択


結果

メニューコマンドとして追加する手順
1. VBA で関数を作成する


Const MENU_ITEM_NAME = "Test"
Private Sub Workbook_AddinInstall() ' アドインのインストール時
With Application.CommandBars("Worksheet Menu Bar") ' メニューコマンド領域
On Error Resume Next
.Controls(MENU_ITEM_NAME).Delete ' メニュー項目追加
On Error GoTo 0
With .Controls.Add(Type:=msoControlButton, before:=.Controls.Count, temporary:=True)
.Caption = MENU_ITEM_NAME ' メニュー名
.OnAction = "Test" ' 実行する関数
.Style = msoButtonIconAndCaption ' ボタンの外観 (https://docs.microsoft.com/ja-jp/office/vba/api/office.msobuttonstyle)
.FaceId = 59 ' ボタンのアイコン (https://www.microsoft.com/en-us/download/details.aspx?id=50745)
End With
End With
End Sub
Private Sub Workbook_AddinUninstall() ' アドインのアンインストール時
With Application.CommandBars("Worksheet Menu Bar")
On Error Resume Next
.Controls(MENU_ITEM_NAME).Delete ' メニュー削除
On Error GoTo 0
End With
End Sub

Sub Test()
MsgBox "Test"
End Sub
2. 1 を xlam ファイルで保存し、一度 Excel を再起動する
C:\Users\ユーザー名\AppData\Roaming\Microsoft\AddIns
に保存
※ Excel を再起動しないと 3 で項目が出てきません。
3. 「開発」タブ >「Excel アドイン」から 2 で保存したファイル名と同じものをチェック


結果
