LoginSignup
3
1

VBAからサクラエディタのGrepを実行し、その結果をVBA上で扱う

Posted at

サクラエディタはコマンドラインからGrepを実行し、その結果を標準出力に出力することができます。

この機能を利用すると、VBAからサクラエディタのGrepを実行し、その結果をVBA上で扱うことが可能です。

サンプルコード

対象のフォルダの配下にあるjavaファイルをGrepし、その結果をResultシートのA列に書き出す。

Sub Main()
    ' 必要な値を定義する
    Dim sakura As String
    Dim gkey As String
    Dim gfolder As String
    Dim gfile As String
    
    sakura = "C:\Program Files (x86)\sakura\sakura.exe"
    gkey = "検索ワード"
    gfolder = "C:\Path\To\Folder"
    gfile = "*.java"
    
    ' コマンドを組み立てる
    Dim command As String
    command = "{0} -GREPMODE -GCODE=99 -GOPT=SPHU -GKEY={1} -GFOLDER={2} -GFILE={3}"
    command = Replace(command, "{0}", """" & sakuraPath & """")
    command = Replace(command, "{1}", """" & gkey & """")
    command = Replace(command, "{2}", """" & gfolder & """")
    command = Replace(command, "{3}", """" & gfile & """")
    
    ' コマンドを実行する
    Dim ws, wse
    Set ws = CreateObject("WScript.Shell")
    Set wse = ws.Exec(command)
    
    ' 実行したコマンドの標準出力を1行づつ読み込み、配列に格納する。
    Dim lines As Collection
    Set lines = New Collection
    Do Until wse.StdOut.AtEndOfStream
        lines.Add wse.StdOut.ReadLine
    Loop
    
    ' コマンドの実行結果をResultシートのA列に書き出す
    Dim line As String
    Dim i As Long
    For i = 1 To lines.Count
        line = lines(i)
        ThisWorkbook.Worksheets("Result").Range("A" & i) = line
    Next i
End Sub

環境情報

image.png

3
1
1

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
1