単純なアウトライン
今回のVBAはファイルの日付を取得し、パワーシェルに入れて変更するというものです。
このため
作成日付、更新日付、最終アクセス日
を変更することができます。
パワーシェルを使うことで、簡単に変更ができます。
今回のはいくつか参照設定が必要ですが、あえて書きません。
なのでこれをコピペしたら動くようにはなっていません。
仮に動かしても、ファイルの作成日時等を取得してそのままもとのファイルに設定するため何も起きません。
Sub testtimestamp()
' For Microsoft Office VBA
' Need Some Reference Setting
' Picuture folderの DSC03292.JPGの作成日時、更新日時、最終アクセス日時を取得し、再びその日付をこのファイルに設定します
' つまり何も起きませんが、ここから他のファイルに設定していくなどのコードに変えていくようになっています。
Const strFile As String = "DSC03292.JPG"
Dim CrDt As Date, MdDt As Date, AcDt As Date
Dim strPath As String
Dim wshr As New IWshRuntimeLibrary.WshShell
Dim FSOR As New FileSystemObject, ret
Dim Attr As Long
Dim Msg As String
strPath = wshr.ExpandEnvironmentStrings("%Userprofile%") & "\Pictures\"
Dim ofile As File
Set ofile = FSOR.GetFile(strPath & strFile)
Dim sCMD As String
CrDt = ofile.DateCreated
MdDt = ofile.DateLastModified
AcDt = ofile.DateLastAccessed
sCMD = "Powershell -command ""Set-executionpolicy remotesigned -scope process -force;[void] [Reflection.Assembly]::LoadWithPartialName(""""""System.Windows.Forms"""""");Add-Type -AssemblyName System.Windows.Forms;[System.Windows.Forms.Clipboard]::Clear();$sFile=""" & _
"'" & strPath & strFile & "'" & """" & _
";$mddt=get-date " & "'" & MdDt & _
"'" & ";$Crdt= get-date " & "'" & CrDt & "'" & _
";$ACDT=get-date " & "'" & AcDt & "'" & _
";set-Itemproperty $sfile -name Creationtime -value $crdt;set-Itemproperty $sfile -name LastWriteTime -value $acdt;set-Itemproperty $sfile -name LastAccessTime -value $acdt;"""
wshr.Run sCMD, 0, True
End Sub
必要性
第一の理由はセキュリティの関係でいえませんが、仕様です。
第二の理由は、Powershellへの送り込みが非常にchar(34)
を多用するのでエラー訂正が大変です。
このため、稼働するサンプルが必要になります。
第三の理由は、更新日時以外はVBAでは基本的に変えるのが困難だからです。
できるサンプルは一つだけで、極めて膨大です。それに比べるとウィルスとして誤検知されることがある程度以外欠点がありません。
RunのWaitは信用できない
また、ExecではなくRunで稼働させるので、返り値がありません。Waitは大量のファイルの場合、効いていないと思えるときがあります。
その場合はSleepなどを使います。
撮影日付はWIAを使う
ここでは紹介しませんが、WIA(Windows Image Aquationwo)を参照設定して使う方法がシンプルでしょう。