我們知道在 Excel VBA 裡,可以用 FileCopy 的方法複製檔案:
Set fs = CreateObject("Scripting.FileSystemObject") '定義fs為一個物件
If fs.fileexists(SourceFile) Then '若來源檔存在
FileCopy SourceFile, DestinationFile ' 將來源檔的內容複製到目的檔中。
但是,若來源檔(SourceFile)已被 Excel 開啟, 程式就會中斷,有什麼辦法能
解決這個問題呢?提出此問題的網友想把 xcopy SourceFile DestinationFile 寫入
DOS批次命令檔(.BAT )中,然後再執行它。我認為既然要用到 DOS, 不如就
直接執行 DOS 的 copy 命令吧:
Sub test()
SourceFile = "c:\test2.xls"
DestinationFile = "c:\ttt.xls"
Set fs = CreateObject("Scripting.FileSystemObject") '定義fs為一個物件
If fs.fileexists(SourceFile) Then '若來源檔存在就呼叫 cmd.exe 來執行 DOS 命令
CmdStr = "cmd /c copy " & SourceFile & " " & DestinationFile
retval = Shell(CmdStr, 0)
End If
End Sub
在上面的程式裡,
CmdStr = "cmd /c copy " & SourceFile & " " & DestinationFile
這一行是組成命令字串, 結果會組成這樣的字串:
"cmd /c copy c:\test2.xls c:\ttt.xls"
copy c:\test2.xls c:\ttt.xls 就是 DOS 的命令, 是把 c:\test2.xls 這個檔案 copy 一份到 c:\test2.xls
cmd 是 Windows 的 cmd.exe 程式, 就是 "命令提示字元"。
/c 這個參數是要它執行後面接著的 DOS 命令。
Shell(CommandString, WinStyle) 是VB呼叫外部程式用的函式。
CommandString 是要執行的命令字串。
WinStyle 是視窗型態, 0 值表是 "不顯示視窗", 所以這個程式執行的時候不會看到 "命令提示字元" 的視窗。
Shell() 會傳回執行結果是成功或有錯誤, 我們可以用 if 或 select case 來檢查 retval 的值。
*註: 不久前在知識+為網友回答這個問題, 稍做整修之後貼在這裡。