将每个Excel文件分别压缩到一个文件夹中。

时间:2017-06-27 14:03:14

标签: excel excel-vba vba

我目前无法尝试压缩文件夹 单独 中的每个文件。我不想压缩文件夹或将所有文件压缩在一起。它们需要单独压缩,以便我以后遍历XML文件夹并提取将要进行OCR的图像。我的尝试是使用VBA并只更改文件扩展名

Sub Create_Zip()

 Dim FSO As FileSystemObject
 Dim objFile As File
 Dim myFolder
 Dim strFilename As String
 Const zipDir As String = "\\...\Zip Test"

 Set FSO = New FileSystemObject
 Set myFolder = FSO.GetFolder(zipDir)

 For Each objFile In myFolder.Files
     strFilename = objFile.Name
     new_strFilename = Replace(strFilename, ".xlsx", ".zip")
 Next objFile
End Sub

根据“即时窗口”,字符串变量“ new_strFilename ”的文件扩展名为“ .zip” 但我没有看到文件夹中的更改。

2 个答案:

答案 0 :(得分:1)

尝试使用将名称A作为B

h = { ... }

hnew = h.inject(h.dup) { |h2, (k, v)|
  h2.merge!(h2.delete(k)) if v.is_a?(Hash)
  h2
}

答案 1 :(得分:1)

您将新文件名分配给变量new_strFilename,但不分配给实际文件。

由于您在尝试objFile.Name = new_strFilename时遇到错误,我认为该属性是只读的。

通常,如果要重命名文件,请使用名称功能:

Name oldFile As newFile

其中oldFile和newFile是包含文件整个路径的字符串。

在你的例子中是这样的:

 For Each objFile In myFolder.Files
     strFilename = objFile.Name
     new_strFilename = Replace(strFilename, ".xlsx", ".zip")

     Name zipDir & "\" & strFilename As zipDir & "\" & new_strFilename
 Next objFile