3
2

More than 3 years have passed since last update.

コードスニペット作成マクロ

Last updated at Posted at 2020-12-18

【VBA】VBEでコードスニペットを扱う仕組み
先日見つけた素晴らしいこの記事を参考に、コードスニペット化マクロを自作してみた。

事前用意

まずはVBEを操作できるようにする。

手順はこちら
Office TANAKA - VBAでVBEを操作する[VBEを操作するための設定]

次に、このマクロ自体を個人用マクロブックSnipetという標準モジュールに登録しておく。

使い方

  1. 何かスニペット化したい部分をコピーしてクリップボードに入れておく
  2. イミディエイトからSNI_00_スニペット作成を呼び出す。("sni"まで打ったらCtrlSpaceで候補が出る
  3. 作成するスニペット名を引数に入れてEnter

すると標準モジュールSnipetの最上段にスニペットが作成される。
別のモジュール名に入れたい場合はここを変える。

ThisWorkbook.VBProject.VBComponents("Snipet").CodeModule 'このモジュールにスニペットを追加する

作成されたスニペットを呼び出すのもイミディエイトから同様に。

コード


Option Explicit

Function SNI_00_スニペット作成(作成スニペット名 As String)
  Dim Codes

  With New MSForms.DataObject
    .GetFromClipboard    '変数のデータをDataObjectに格納する
    Codes = Split(.GetText, vbCrLf)
  End With

  Dim ub: ub = UBound(Codes)

  Dim Snipets
  ReDim Snipets(ub)
  Dim i
  For i = 0 To ub
    Codes(i) = Replace(Codes(i), """", """""")  ' 既存ダブルクォーテーションを生かす処理
    Snipets(i) = "  debug.Print " & """" & Codes(i) & """"  '全体のダブルクォーテーションのエスケープ処理
  Next

  Dim buf
  buf = Join(Snipets, vbLf)
  buf = "Function SNI_" & 作成スニペット名 & "()" & vbLf & buf
  buf = buf & vbLf & "End Function"

  With ThisWorkbook.VBProject.VBComponents("Snipet").CodeModule 'このモジュールにスニペットを追加する
    .AddFromString buf
  End With

End Function

3
2
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
3
2