masatoの日記

やっていきます

VBAを使ってOfficeからコマンドプロンプトであれこれやる

VBAからコマンドプロンプトにコマンドを渡して実行できる。 これはつまり、WordとかExcelとかから外部プログラムを実行できるということだ。

ためしに、Excelのシートにある文字列をKakashiを使ってわかち書きするということをやってみる。

ネタとして、夏目漱石『坊ちゃん』の冒頭部分を青空文庫からひろってきた。 f:id:masatoz:20170706213159p:plain

坊ちゃんの文章を入れたとなりのセルにコマンドを実行するための関数をいれる。この関数は、ユーザー定義関数というやつで、ようは自分で書いた関数だ。

f:id:masatoz:20170706213149p:plain

組み込み関数みたいにワークシートから実行できる関数は↓のようにして書ける。

Public Function wakachi_gaki(Cell As Range)
    Dim pipe As String: pipe = Chr(124) ' パイプ(|). ハードコードしたら失敗した

    Dim WSH As Object
    Set WSH = CreateObject("WScript.Shell")
    
    Dim sCmd As String
    sCmd = "echo " & Cell.Value & " " & pipe & " kakasi -w" ' コマンドのあいだにスペース必要
    
    Dim wExec
    Set wExec = WSH.Exec("%ComSpec% /c " & sCmd)
    
    '処理が終わるまでまつ
    Do While wExec.Status = 0
        DoEvents
    Loop

    wakachi_gaki = wExec.StdOut.ReadAll
    
    Set wExec = Nothing
    Set WSH = Nothing
End Function

関数を入力してエンター。 一瞬、コマンドプロンプトがちらっと表示される。

分かち書きできている。

f:id:masatoz:20170706213407p:plain

コマンドプロンプトで実行できるということは、Perlもつかえるということだ。 ためしてみた。

かんたんに試すだけなので、Perlのバージョンを表示させてみた。

perl -vってやるだけ。

This is perl 5, version 24, subversion 0 (v5.24.0) built for MSWin32-x64-multi-thread

Copyright 1987-2016, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using ""man perl"" or ""perldoc perl"".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

ちゃんと返ってきた。

これはVBAと多言語のインターフェイスとしてつかえる。

コードはこれ。

Public Function perl(cmd As String)

    Dim WSH As Object
    Set WSH = CreateObject("WScript.Shell")
    
    Dim wExec
    Set wExec = WSH.Exec("%ComSpec% /c " & cmd)
    
    '処理が終わるまでまつ
    Do While wExec.Status = 0
        DoEvents
    Loop

    perl = wExec.StdOut.ReadAll
    
    Set wExec = Nothing
    Set WSH = Nothing
End Function