Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip batch command and Excel

I have many excel files that I need zipped into each of their own zip folders. I thought I had this ironed out, but I have co-workers coming back to me saying that they cannot open the excel file because it has become corrupted. I went back and checked the original file, and it opens up just fine. But when I open up the same version of the file that was zipped, I too get the corrupted error. I'm on Office 2010, which is able to repair it, but my co-workers are all Office 2007 which does not seem to be able to fix the file. My batch code is as follows:

for /r %%X in (*.xlsm) do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%~nX" "%%X"
like image 609
JHStarner Avatar asked Jul 18 '26 18:07

JHStarner


2 Answers

I think you might be using a wrong value as the first parameter to the 7zip executable. According to the documentation on FOR:

%~nI - expands %I to a file name only

And according to the 7zip documentation:

You can use the "a" command with the single letter a. This command stands for 'archive' or 'add'. Use it to put files in an archive. You have to specify the destination archive, and the source files (in that order).

So, using your script with an example file, it seems to me that your command line becomes:

"C:\Program Files\7-Zip\7z.exe" a -tzip "somefile.xlsm" "C:\path\to\somefile.xlsm"

Shouldn't the first parameter have a .zip file extension on the end? So the line is modified to look like this:

for /r %%X in (*.xlsm) do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%~nX.zip" "%%X"

As annoying as it is, file extensions actually mean something in Windows. Your previous line was creating a zip file with the .xlsm extension. When people try opening those files, Excel complains (because it's a zip file; not a .xlsm).

like image 70
Jonah Bishop Avatar answered Jul 21 '26 10:07

Jonah Bishop


@Echo OFF
PUSHD "C:\Program Files\7-Zip" && (
    FOR /R "%CD%" %%# in (*.xlms) DO (7z a -tzip "%%~n#.zip" "%%#")
    POPD
)
REM Don't worry about the PUSHD command, the %CD% variable isn't expanded, that's the trick.
Pause&Exit

And you can use the dynamic operator * (asterisk) and 7zip -recursive parameter if you want all together in one file:

7z a -r -tzip "ALL.zip" "*.xlsm"
like image 25
ElektroStudios Avatar answered Jul 21 '26 12:07

ElektroStudios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!