ExcelVBA Text File 作成方法の応用

昨日の「しごと」で書いた内容…最初はバッチスクリプトExcel から書き出すために使っていたものだった。
これが、結構便利。
UNIXのシェル環境ほどではないにせよ、コマンドプロンプトも使えるようになってきている。
遅きに失したというか、GUI(見た目)を優先した結果なんだろうけど。


今日は、備忘のためもあって登録。

前提

次の知識があることを前提に記述。


内容的には、%tmp%*1 に sample.log というファイルがあったら、notepad で起動するという処理。
作りこみはいろいろなやり方があるので、飽くまでもシンプルに。

@echo off
rem sample command script

if not exist %tmp%\*.log goto NotExistFile
start notepad.exe %tmp%\sample.log

:NotExistFile

上記のコマンドラインVBAで書かせる。

Function CreateCMD() 

Dim WorkPath As String

WorkPath = "c:\sample.cmd"

If vbOK = MsgBox("次のディレクトリに出力します" & vbCr & vbLf _
	& "    " & _
	WorkPath & vbCr & vbLf & "よろしいですか?", vbOKCancel, "出力パス確認") Then
	With CreateObject("Scripting.FileSystemObject").CreateTextFile(WorkPath, True)
	        .WriteLine ("@echo off")
	        .WriteLine ("rem sample command script")
	        .WriteLine ("")
	        .WriteLine ("if not exist %tmp%\sample.log goto NotExistFile")
	        .WriteLine ("start notepad.exe %tmp%\sample.log")
	        .WriteLine ("")
	        .WriteLine (":NotExistFile")
	End Function
End If

コツという程でもないけれど、先にVBAで作らせたいバッチを作ってからVBAでコーディングしていくと間違いが少ない。


しかし…C言語とか、JAVAとか、今の主要な言語を扱えない僕…少し悲しかったり。

*1:%tmp% = C:\Documents and Settings\USER NAME\Local Settings\Temp