前陣子做個項(xiàng)目要頻繁壓縮文件,到處找壓縮文件的代碼總沒找到合適的,只好自己動手了。本過程實(shí)現(xiàn)調(diào)用系統(tǒng)安裝的winrar軟件完成壓縮多文件及文件夾功能,其實(shí)際效果等同與在文件夾里選擇多個文件及文件夾后右鍵壓縮功能 ,本代碼最大的好處是壓縮文件夾時不會帶根目錄 , 非常適用于文件及文件夾混合壓縮 ,可指定壓縮后目錄。
示例代碼如下'****VBA壓縮文件********Copyright@2015 www.excle880**************************************
'*將filelist文件或文件夾列表壓縮到rarname文件中 注意都是用絕對路徑 filelist之間逗號分隔
'*eg. E8_RarFiles "D:\Documents\Desktop\2.rar", "D:\Documents\Desktop\2\2,D:\Documents\Desktop\2\1.txt"
'****作者:excel880 *******************************************************
Sub E8_RarFiles(rarname, filelist)
Dim Source As String '壓縮前的原始文件
Dim Target As String '壓縮后的目標(biāo)文件
Dim cmdstr As String 'Shell指令中的字符串
Dim Rarexe As String 'WINRAR執(zhí)行文件的位置
Dim arr, dic, i, n, k, iitem, ks
Rarexe = "C:\program files\winrar\winrar"
arr = Split(filelist, ",")
Set dic = CreateObject("scripting.dictionary")
For i = 0 To UBound(arr)
n = InStrRev(arr(i), "\")
k = Left(arr(i), n - 1)
iitem = """" & Mid(arr(i), n + 1) & """"
dic(k) = dic(k) & " " & iitem
Next
ks = dic.keys
rarname = """" & rarname & """" '空格路徑 加雙引號
For i = 0 To dic.Count - 1
ChDrive ks(i)
ChDir ks(i)
Source = dic(ks(i))
cmdstr = Rarexe & " a " & rarname & " " & Source
Shell cmdstr, vbHide
Next
End Sub
Private Sub Test()
Dim i&, j&, k&, arr, brr, s
s = ThisWorkbook.Path & "\"
E8_RarFiles s & "test.rar", s & "1.txt," & s & "2.txt," & s & "1 2 3"
End Sub
聯(lián)系客服