Zip All Files in Folder - vba

I have been using a snippet of VBA for years to zip all files in a folder. Today we tried this on a co workers computer and the code appears to go through its iterations but there is not any files output. The only difference is the new machine is 32 bit and the old code is for 64 bit. Is there any reason the 32 bit file would not work with VBA?
Sub ZipIndividualFiles1()
Dim file As Variant
Const source = "C:\Users\co01\Desktop\TEST"
Const DEST = "C:\Users\co01\Desktop\Zipped"
Const PATH_TO_7Z = "C:\Program Files\7-Zip\7z.exe"
For Each file In CreateObject("Scripting.FileSystemObject").GetFolder(source).Files
Shell PATH_TO_7Z & " a -tzip """ & DEST & "\" & file.Name & ".zip"" """ & file.Path & """"
Next
End Sub
7 zip exists at the PATH_TO_7Z path. We even tried re-installing it. The program runs to completion without error.

Hi i found this code that will do the job, that you need to place it the folder you need to zip and just run it and you can save as batch file execute via VBA.
I learned this recently so i like to indicate the changes that can be made.
If you need the script to zip all files as individual zip then you need to modify "%CurrDirName%.zip" to "%%a.zip"
If you need the script to zip all contents in to one you can change "%%a.zip" to "%CurrDirName%.zip
If you need to provide a name the simple you can hard coded the name there "Hardcoded.zip"
If you need to zip only certain file types you can add them in set extension
If you need to zip excluding certain file types you -x!*.bat, here .bat is what i am excluding
Hope it helps
#echo off
cd /d %~dp0
rem 7z.exe path
set sevenzip=
if "%sevenzip%"=="" if exist "%ProgramFiles(x86)%\7-zip\7z.exe" set sevenzip=%ProgramFiles(x86)%\7-zip\7z.exe
if "%sevenzip%"=="" if exist "%ProgramFiles%\7-zip\7z.exe" set sevenzip=%ProgramFiles%\7-zip\7z.exe
if "%sevenzip%"=="" echo 7-zip not found&pause&exit
for %%I in (.) do set CurrDirName=%%~nxI
set extension=.*
for %%a in (*%extension%) do "%sevenzip%" a "%CurrDirName%.zip" "%%a" -x!*.bat
pause
[/CODE]

Related

How to indicate a directory path using variables?

I have to implement the use of a certain .exe file in VBA. The .exe takes as input a specific type of file and outputs a .txt file.
When I write the whole directory of both the input and output files, the code works. When I split the directory and store the parts in variables, it doesn't.
I need to split it because I am going to use this .exe with different directories so the user could choose the wanted directory.
Sub convert()
Dim directory As String
Dim Filename As String
directory = "C:\Users\user1\Desktop\reporting\201703161224"
Filename = "\input.set"
Shell "cmd /c""C:\Users\user1\Desktop\reporting\appli.exe
C:\Users\user1\Desktop\reporting\201703161224\input.set>
C:\Users\user1\Desktop\reporting\201703161224\output.txt"
'this works well
file = directory & Filename
Shell "cmd /c""C:\Users\user1\Desktop\reporting\appli.exe file>
C:\Users\user1\Desktop\reporting\201703161224\output.txt"
'this doesn't work
End Sub
You need to break out of the quotes and Concatenate to use your file string variable
Shell = "Hard_Coded_String_1" & file & "Hard_Coded_String_2"

What is the difference between Program and Argument directories when calling .exe using Shell in VBA?

My latest attempt to solve my problems when calling a .exe with an input argument from Excel-VBA uses this script:
Sub RunProgram()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
ChDir "\\path\folder1\folder2\"
StartExeWithArgument
......
End Sub
Public Sub StartExeWithArgument()
Dim strProgramName As String
Dim strArgument As String
strProgramName = "program.exe "
strArgument = "datafile.gdp"
Call Shell("""" & strProgramName & """ """ & strArgument & """", vbNormalFocus)
End Sub
The path I set as the working directory is the working directory of the .exe program, and the location of the input file datafile.gdp. However, this current script calls the .exe without loading the argument file and the calculations the .exe is supposed to run do not occur. Instead the .exe launches to its main page as though I clicked a desktop shortcut to start a new project. When loaded correctly, the .gdp file should cause the calculation to initiate and run in the background without ever appearing to the user.
If I change the path of the input file to:
strArgument = "\\path\folder1\folder2\datafile.gdp"
But keep everything else the same, the .exe launches and calculates automatically, but wants to write files in the following duplicated directory, (all prefixed with the name of the input file):
\\path\folder1\folder2\PATH\FOLDER1\FOLDER2\
If I create the file path for it to operate in everything operates as it should, BUT the path is actually 6 folders deep in reality and this is all being duplicated, meaning the files are too deep to be backed up on our system. So I need to launch the program and have it operating without this duplication of the directory. It works fine when not launched from this VBA script, and worked fine before the .exe was updated by an external company.
Why can the Call Shell command find the .exe without a path, but I
need to provide a path for the argument?
strArgument = ... requires a path to find the argument file, despite the file being in the current directory, providing the path seems to pass a duplicated path to the .exe causing it to crash if I don't create the folders representing the duplicated directory so it can operate within them. Is there something very basic I am missing regarding directories?
My previous up-voted but unanswered question here provides more context.

VBA MkDir silently removes caron

I am using VBA to create folders automatically. One of the folder names that I need to create contains the character č (c with caron). When I use MkDir in VBA the folder is created with a "c" instead of a "č".
Sample code:
root_folder = "C:\customers\"
folder_name = "háček" 'I do not think you can enter this into the VBA editor, but I am getting the folder_name from an external source
full_folder_path = root_folder & folder_name & "\"
MkDir full_folder_path
attachment.SaveAs full_folder_path & attachment.filename
This will create a folder called "C:\customers\hacek\" instead of "C:\customers\háček\", which then causes the save operation to fail, because it tries to save in "C:\customers\háček\, which of course does not exist. VBA seems to be able to read and handle the characters correctly, because I can read it from my data source and save it to a text file without issues. The problem just seems to exist when it comes to creating folders.
Is there a way to make VBA create the folder with the name that I have actually specified?
edit: formatting
If you use FileSystemObject, you are able to create the Folder with the proper name:
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
fs.CreateFolder "C:\customers\hac" & ChrW(269) & "ek" 'ChrW(269) prints č

excel vba won't execute .bat but manually executing bat works fine

Hi I have a perfectly working bat named: start.bat
containing:
start C:\Users\*user*\Documents\*path*\hidebat.vbs
and once it is manually opened it works perfectly, meaning it opens hidebat.vbs, which opens a .bat minimized which uploads files to my cloud. Hence it's verified.
I've added
pause
to the start.bat to see what it does and when I tell excel to open the start.bat it will open cmd and display the exact command as required, but it will not execute the hidebat.vbs.
I expect that there is somehow some path constraint or environment constraint when it is run from excel that prevents it to actually reach out of that limited environment.
Within excel I have tried calling the .bat in 3 different ways with:
Dim path As String
path = Application.ActiveWorkbook.path
path = path & "\"
Dim MY_FILENAME3 As String
MY_FILENAME3 = path & "start.bat"
1.
retVal = Shell(MY_FILENAME3, vbNormalFocus)
' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
MsgBox "An Error Occured"
Close #FileNumber
End
End If
2.
PathCrnt = ActiveWorkbook.path
Call Shell(PathCrnt & "start.bat")
3.
Dim batPath As String: batPath = path
Call Shell(Environ$("COMSPEC") & " /c " & batPath & "start.bat", vbNormalFocus)
Does anybody have any clue on why it will not execute the .bat file, or what I could do to ensure it will run correctly?
Note. I think it is because it opens the default path, so I'm gonna tell it to "cd" to the actual path where the excel is saved and where the .bat files are.
Yes that was it, the path was set to some random/standard/working/current path by command, so I had to add:
Print #FileNumber, "cd " & path
to the excel macro
so that start.bat looked like:
cd *path*
start *path*\hidebat.vbs
Hope this helps future me's.

Kill Command Deleting Wrong File(s)i

In Access VBA, I have a procedure I've put together to do this:
Allow the user to select zip file(s)
Extract any files from the zip files to the same directory (In this
specific use-case instance, it is ALWAYS extracting Excel files from
Zip files, never any change, and always using the same password)
Then I want the code to Delete the Zip file after extracting the
.xls file.
Everything works beautifully except the delete file portion. The issue is that when I tell it to delete "FileName.Zip", it is deleting "FileName.Zip" AND "FileName.xls"
Is there any way to make sure that he kill command ONLY deletes what I want it to delete? I've used it before on various occasions, and never had this happen before.
Here is the code I am using:
Dim fd As FileDialog
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Variant
Set db = CurrentDb
Set rs = db.OpenRecordset("tblProjectPath")
Set fd = FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = True
fd.Title = "Select TOC Return File(s) to process"
fd.InitialFileName = rs.Fields("ProjectPath") & "\FilingReports\*.zip"
fd.Show
For Each i In fd.SelectedItems
'Debug.Print i
Debug.Print '------------------------'
Debug.Print i
Unzip (i) 'The bit calling the command line unzip utility to unzip the file - just telling it to extract all files to the current folder.
Debug.Print i
'Kill i
'had to take out the kill bit, b/c it was deleting both the .zip and .xls files which is not desired nor expected
If InStr(i, ".zip") Then
Kill i 'Tried to specify only .zip files even though think I shouldn't need to, but it's still deleting .xls files
End If
Next i
Edit: Add Unzip code to post:
Unzip code:
Sub Unzip(Path As String)
Dim strUnzip As String
Dim QU As String 'quotation mark
QU = Chr(34)
strUnzip = QU & "c:\program files (x86)\winzip\wzunzip" & QU & " -s" & _
"ZipPassword " & _
Path & " " '& _
Call Shell(strUnzip)
End Sub
At this point, I don't really think a "real" answer will come about. However, I'll post what I've decided to do with the particular process I'm writing this code for anyway.
I'm going to use a folder structure to divide up the files:
1. Place zip file(s)
2. Unzip files to a 2nd folder
3. After processing Excel files in 2nd folder, move to a 3rd "complete" folder.
This will get around the deleting wrong files bit.
Also, it appears that the cause for the issue is related to something to do with the call to the WinZip Command Line Unzip utility (wzunzip) in the Unzip code above, or else something with the tool itself. I thought that maybe it was b/c the tool was asking me if I wanted to overwrite existing files, but that wasn't the case, b/c I had the same issue when there were no files to overwrite.
Anyway, I'm attempting to close this one up at this point. Thanks to Wayne G. Dunn for his assistance on this.