Excel操作 SASマクロ

【SAS】既存のExcelファイルのパスワードを設定・解除する(STREAM、VBScript)

以下のサイトを参考にさせていただいてます。
SAS One Dash

1.展開例

・パスワードを設定する

パスワードを設定する場合は、引数outpwに任意のパスワードを指定します。
既存のパスワードを上書きする場合は、既存のパスワードを引数inpwに指定して下さい。

%password_excel(file=C:\Blog\SAS\export_excel\都道府県.xlsx, inpw=, outpw=x9999);

password_excel
 

・パスワードを解除する

パスワードを解除する場合は、解除したいパスワードを引数inpwに指定し、引数outpwを省略します。

%password_excel(file=C:\Blog\SAS\export_excel\都道府県.xlsx, inpw=x9999, outpw=);

引数inpwと既存のパスワードが異なる場合、以下のようなエラーが出ます。
password_excel_error
 

2.参考プログラム

以下は、参考プログラムになります。
右上のコピーボタンを押せば、プログラム全体をコピーできます。

%macro password_excel(file=, inpw=, outpw=);
%put --------------------------------------------------;
%put password_excel;/*既存のExcelファイルのパスワードを設定・解除する*/
%put &=file;		/*パスワード設定・解除したいExcelファイルをフルパスで指定*/
%put &=inpw;		/*解除するパスワードを指定(省略可)*/
%put &=outpw;		/*設定するパスワードを指定(省略した場合はパスワードが解除されて上書き保存される)*/
%put --------------------------------------------------;

	%let path=%substr(%superq(file), 1, %length(%superq(file))-%length(%scan(%superq(file), -1, '\'))-1);
	%if %substr(%superq(path), %length(%superq(path))) = \ %then %do;
		%put ERROR: fileのバックスラッシュの入力が不正です。 &=file;
		%abort;
	%end;

	filename path "%superq(path)";
	option noxwait xsync;

	/* パスワード設定 */
	data _null_;
		call symputx("path",pathname("path"));
		text="'"||tranwrd(strip(pathname("path")),'','" "')||'\エクセルパスワード設定.vbs'||"'";
		call symputx("xcommand",text);
	run;

	filename vbs "&path.\エクセルパスワード設定.vbs" encoding="sjis";
	proc stream outfile=vbs resetdelim="br"; begin
	Set ex=CreateObject("Excel.Application") br newline;
	ex.Visible=True br newline;
	ex.Workbooks.Open("%superq(file)") %if %length(&inpw.) > 0 %then ,,,,"&inpw."; br newline;
	ex.DisplayAlerts=False br newline;
	ex.ActiveWorkbook.ReadOnlyRecommended=false br newline;
	ex.ActiveWorkbook.SaveAs "&file." %if %length(&outpw.) > 0 %then ,,"&outpw."; br newline;
	ex.Quit
	;;;;
	filename vbs clear;

	data _null_;
		call system(&xcommand.);/* vbs実行 */
		rc=filename("vbs","&path.\エクセルパスワード設定.vbs");
		rc=fdelete("vbs");		/* vbs削除 */
	run;

	option noxsync;
	filename path clear;

%mend password_excel;