5
8

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 5 years have passed since last update.

VBAからWinMergeを起動する方法

Last updated at Posted at 2019-09-09

はじめに

VBAからWinMergeを起動する方法について忘備録として残しておきます。

Excel

以下のように差分を取りたい対象のフルパスが入った表を用意します。
キャプチャ.PNG

ここでは同じ行のファイル1とファイル2を比較します。

コード

Sub ExecWinMerge()

    '結果
    Dim rc As Long
    '選択セル(WinMerge比較)の行番号
    Dim targetRow As Long
    '選択セル(WinMerge比較)と同じ行の対象ファイル1
    Dim targetFile1 As String
    '選択セル(WinMerge比較)と同じ行の対象ファイル2
    Dim targetFile2 As String
    'WinMerge の実行ファイル
    Dim winExeFile As String
    '実行時の引数を結合した文字列
    Dim exeStr As String
    
    '選択しているD列の行番号を取得
    '例)D2を選択している場合は2
    targetRow = Selection.Row
    '対象ファイル1のパスを取得
    '例)D2を選択している場合は(2,2)
    targetFile1 = Cells(targetRow, 2)
    '対象ファイル2のパスを取得
    '例)D2を選択している場合は(2,3)
    targetFile2 = Cells(targetRow, 3)
    'WinMergeの実行ファイルを指定
    '/eを指定することでescキーで閉じられるようにしている
    winExeFile = "C:\PROGRA~1\WinMerge\WinMergeU.exe /e "
    '文字列を結合して実行時のコマンドを作成
    '例)C:\PROGRA~1\WinMerge\WinMergeU.exe C:\vbaSample\before\test1.txt C:\vbaSample\after\test1.txt
    exeStr = winExeFile & " " & targetFile1 & " " & targetFile2
    
    'WinMerge起動
    rc = Shell(exeStr, vbNormalFocus)
    
    'エラー処理
    If rc = 0 Then MsgBox "起動に失敗しました"

End Sub

その他

ショートカットキーを設定することで、D列の選択行の対象ファイル1と対象ファイル2の比較がよりやりやすいです。

また、WinMergeの実行ファイルの指定について、コマンド上で半角スペースを含んだ「Program Files」では正しく認識されないため「PROGRA~1」としています。

正しく認識されない例
C:\>C:\Program Files\WinMerge\WinMergeU.exe C:\vbaSample\before\test1.txt C:\vbaSample\after\test1.txt
'C:\Program' は、内部コマンドまたは外部コマンド、
操作可能なプログラムまたはバッチ ファイルとして認識されていません。

参考

https://so-zou.jp/software/tech/tool/diff/winmerge/commandline/
https://www.itmedia.co.jp/help/tips/windows/w0140.html

5
8
2

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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?