Excel VBA で 特定のフォルダに保存する AppleScript を作成する

December 3, 2020
excel vba Mac Excel for Mac

Excel VBA で 特定のフォルダに保存する AppleScript を作成する

前回で VBA から AppleScript を作成する方法を紹介しました。AppleScript の作成は成功しましたが、~/LibraryApplication Scripts/com.microsoft.Excel/ という特定のディレクトリにユーザー自身が保存してもらう必要が生じます。しかもこのディレクトリは開くのに特殊な操作をしなければなりません。

負担のある作業をなんとか VBA でできないか試行錯誤した記録を書いてみます。

特定ディレクトリにテキストファイルを保存する AppleScript を VBA から出力する

VBA からアクセスできないなら、AppleScript (以降はスクリプト)でアクセスをしようという作戦です。すでにスクリプトを出力する VBA は作成した経験があるので、それをベースにスクリプトを変更してみます。

テキストファイルを保存するスクリプトコード

set root to (path to home folder) as string
set mkEdir to root & "Library:Application Scripts:"
set tgtpath to root & "Library:Application Scripts:com.microsoft.Excel:"
set mkas to tgtpath & "test.txt"

set asval to "Hello VBA for Mac"

tell application "Finder"
	if not (exists tgtpath) then
		make new folder at mkEdir with properties {name:"com.microsoft.Excel"}
	end if
end tell

try
	set tfile to open for access file mkas with write permission
	set eof of tfile to 0
	write asval to tfile
end try

close access tfile

tell application "Finder"
	open tgtpath
end tell

” Hello VBA for Mac “ の内容の test.txt を特定のディレクトリに保存します。


VBAコード

Sub createAs()

Dim root As String
Dim path1 As String
Dim appscript As String

root = ThisWorkbook.path
path1 = root & Application.PathSeparator & "test.scpt"

applescript = "set root to (path to home folder) as string" & vbNewLine & "set mkEdir to root &" & """" & "Library:Application Scripts:" & """" & vbNewLine & "set tgtpath to root &" & """" & "Library:Application Scripts:com.microsoft.Excel:" & """" & vbNewLine & "set mkas to tgtpath &" & """" & "test.txt" & """" & vbNewLine & "set asval to" & """" & "Hello VBA for Mac" & """" & vbNewLine & "tell application " & """" & "Finder" & """" & vbNewLine & "if not (exists tgtpath) then" & vbNewLine & "make new folder at mkEdir with properties {name:" & """" & "com.microsoft.Excel" & """" & "}" & vbNewLine & "end if" & vbNewLine & "end tell" & vbNewLine & "try" & vbNewLine & "set tfile to open for access file mkas with write permission" & vbNewLine & "set eof of tfile to 0" & vbNewLine & "write asval to tfile" & vbNewLine & "end try" & vbNewLine & "close access tfile" & vbNewLine & "tell application " & """" & "Finder" & """" & vbNewLine & "open tgtpath" & vbNewLine & "end tell"

Open path1 For Output As #2
    Print #2, applescript
Close #2

End Sub

スクリプトの VBA インライン化がかなり大変です。改行でコードの判定しているコード同士の相性の悪さを久しぶりに味わいました。

実行結果

成功しました。特定ディレクトリにテキストファイルが保存されました。

VBA 実行前


VBA 実行後

スクリプトをダブルクリック

スクリプトは開いてから、実行する必要があります。


スクリプト実行結果

保存した特定ディレクトリを開きます。 test.txt が保存されている事がわかります。


保存内容

問題点

スクリプトをダブルクリックで起動できないのはやはり不便ではあります。ただ、機能追加の度にApp化するのは現実的ではありませんし、ユーザーの手数も結果的に変わらないように思えます。

問題点はありますが、可能性のある結果になったと思っています。

Next Previous

3つの表

October 12, 2023
excel データ入力 操作

Excelで量産シミュレーション

October 12, 2023
excel データ入力 操作

テーブルについて

October 12, 2023
excel データ入力 操作