Winzip not executing with gap in file path - vba

I've used the code from Extract all .gz file in folder using VBA Shell command, to extract .gz files.The problem is that if there is a gap in the filepath, code doesn't work, if there is no gap, it works, as illustrated below:
Notice in first example, there is no '_' but a gap ' ', between 'K' and 'L', therefore file path has gaps,
whereas example that works, there is an '_', and the whole filepath has no gaps
'Example that doesn't work:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, File As Variant
Dim shellStr As String
File = Dir("Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\*.gz")
While (File <> "")
If InStr(1, File, ".gz") > 0 Then
shellStr = "C:\Program Files\WinZip\winzip32 -e Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\" & File & " Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\"
Call Shell(shellStr, vbHide)
End If
File = Dir
Wend
End Sub
'Example that works:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, File As Variant
Dim shellStr As String
File = Dir("Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\*.gz")
While (File <> "")
If InStr(1, File, ".gz") > 0 Then
shellStr = "C:\Program Files\WinZip\winzip32 -e Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\" & File & " Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\"
Call Shell(shellStr, vbHide)
End If
File = Dir
Wend
End Sub
I want the first example to work, but why doesn't it?
There are no errors. The code runs, opens winzip, but it's empty, no file is unzipped!
Many thanks.

Try putting quotation marks around the paths in your shell string:
shellStr = "C:\Program Files\WinZip\winzip32 -e ""Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\" & File & """ ""Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\"""
In case you didn't already know, two double quotes ("") evaluates to a single double quote inside the string. Compare to languages like C where the backslash would be used to escape the quotation mark (\").

Related

Search for file in folder backwards

So far all the examples for checking if a file is in a directory has been to get a list of files in that directory then compare your items to it. This is a lot of overload for me. I have a list of about 125 files and the directory I want to search in has 8000 files. Can someone instruct me on how to use a file with a list of file names and search a directory for each file.
Moved here from comments:
The code below works, but because it's searching through 8000 files in
a directory the code takes a long time to work. I have a document with
350 lines of file names. Instead of going through each file in the
directory for a match to one of the file names in my document. I'd
like to take my list and search the directory for that file. This way
I'm only looping 350 times instead of 8000
Here is my code.
Dim fileNames As String() = System.IO.Directory.GetFiles(imgLocation)
Dim i As Integer
statusText = "Copying Image Files"
i = 0
' Loop over the filenames retrieved
For Each fileName As String In fileNames
' Check if the files is contained or not in the request list
If GraphicList.Contains(Path.GetFileNameWithoutExtension(fileName)) Then
'Debug.Write("Filename " & fileName & vbCr)
Dim FileNameOnly = Path.GetFileName(fileName)
Dim copyTo As String
copyTo = createImgFldr & "\" & FileNameOnly
System.IO.File.Copy(fileName, copyTo, True)
' Do not write to file inside the loop, just add the fact to the list
' Debug.Write("Copy image " & FileNameOnly & vbCr)
imgFilename = (FileNameOnly) + vbCrLf
ImageCount1 = i
BackgroundWorker1.ReportProgress(100 * i / GraphicList.Count())
foundImgFiles.Add(FileNameOnly)
Else
Debug.Write("Missing " & FileNameOnly & vbCr)
notfoundImgFiles.Add(fileName)
End If
i = i + 1
Next

VBA excel: how to add text to all files on a folder

I need to add text string to all files on a folder, as a footer
For example, on the folder on the path and called C:\mobatchscripts\
I have a random number of txt files, with text.
I want to add a line for example "text" on each of the text files on the folder
I have little knowledge of vba programming, but for what I have read I can use append, but I need something that loop on the files on the folder, and modify them.
So far I tried this:
Sub footer()
Dim FolderPath As String
Dim FileName As String
Dim wb As Excel.Workbook
FolderPath = "C:\mobatchscripts\"
FileName = Dir(FolderPath)
Do While FileName <> ""
Open FileName For Append As #1
Print #1, "test"
Close #1
FileName = Dir
Loop
End Sub
But seems that its not looking into the files, or appending the text.
On the assumption that you're writing to text files (I see "batchscripts" in the path), you need a reference to the Microsoft Scripting Runtime (Within the VBE you'll find it in Tools, References)
Option Explicit
Public Sub AppendTextToFiles(strFolderPath As String, _
strAppendText As String, _
blnAddLine As Boolean)
Dim objFSO As FileSystemObject
Dim fldOutput As Folder
Dim filCurrent As File
Dim txsOutput As TextStream
Set objFSO = New FileSystemObject
If objFSO.FolderExists(strFolderPath) Then
Set fldOutput = objFSO.GetFolder(strFolderPath)
For Each filCurrent In fldOutput.Files
Set txsOutput = filCurrent.OpenAsTextStream(ForAppending)
If blnAddLine Then
txsOutput.WriteLine strAppendText
Else
txsOutput.Write strAppendText
End If
txsOutput.Close
Next
MsgBox "Wrote text to " & fldOutput.Files.Count & " files", vbInformation
Else
MsgBox "Path not found", vbExclamation, "Invalid path"
End If
End Sub
I'd recommend adding error handling as well and possibly a check for the file extension to ensure that you're writing only to those files that you want to.
To add a line it would be called like this:
AppendTextToFiles "C:\mobatchscripts", "Test", True
To just add text to the file - no new line:
AppendTextToFiles "C:\mobatchscripts", "Test", False
Alternatively, forget the params and convert them to constants at the beginning of the proc. Next time I'd recommend working on the wording of your question as it's not really very clear what you're trying to achieve.

Converting Dos Text Files to Unix in VBA fails

I've followed the suggestion in a prior question and grabbed this code but I don't get a useable file out of it. I've looked at it and don't see the problem.
Public Enum ConvertType
dos2unix = 0
unix2dos = 1
End Enum
Public Function ConvertFile(OriginalFile As String, NewFile As String, eConvertType As ConvertType, _
Optional DeleteOriginal As Boolean = False)
Dim OpenFileNum, SaveFileNum As Integer
Dim NewFileBuffer As String
' This function will open a file and convert it to
' a txt file format usable under *nix or dos
On Error GoTo Error_Found
OpenFileNum = FreeFile ' grab the first free file
Open OriginalFile For Input As #OpenFileNum ' open the unix file
SaveFileNum = FreeFile ' get another free file to write to
Open NewFile For Binary As #SaveFileNum ' open/create the save file
Do While Not EOF(OpenFileNum)
Line Input #OpenFileNum, NewFileBuffer ' retrive the text (if a unix file, then the entire text is on one line)
If eConvertType = dos2unix Then ' Check what type of conversion to do
NewFileBuffer = NewFileBuffer & Chr(10)
Else
NewFileBuffer = Replace(NewFileBuffer, Chr(10), vbCrLf)
End If
Put #SaveFileNum, , NewFileBuffer ' write out the file
Loop
Close #SaveFileNum
Close #OpenFileNum
If DeleteOriginal = True Then Kill OriginalFile
Exit_Sub:
Exit Function
Try this:
Option Explicit
Sub testConversion()
convertFile "C:\test.txt"
End Sub
Public Sub convertFile(ByVal fileName As String)
Const Dos2Unix = 1
Dim fs As Object, txt As String
Set fs = CreateObject("Scripting.FileSystemObject")
txt = fs.OpenTextFile(fileName, 1).ReadAll 'ForReading = 1
txt = IIf(Dos2Unix = 1, Replace(txt, vbCrLf, vbLf), Replace(txt, vbLf, vbCrLf))
fs.OpenTextFile(fileName, 2).Write txt 'ForWriting = 2
End Sub
Notes:
In Notepad (Windows) all lines will appear on one continuous line
All CarriageReturn–Linefeed combinations are replaced by Linefeed characters

Search a folder for keyword

I'm looking to search a folder for a keyword term 'fuel', to pull information from returned files into a 'data' sheet.
For instance, I have a folder week numbers (1 - 52 cross the year so in the new year this will contain one folder but will build as the year goes on).
I search this folder for all .doc files contains the word 'fuel'.
You can do this via a Windows search by typing "fuel" in the search function in the top corner and it will display all filenames and all files that contains the word 'fuel'.
I have this for searching for a file that has 'fuel' in its name, but not inside it.
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "fuel") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub
It isn't particularly pretty, but think something like this should work:
Sub loopThroughFiles()
Dim file As String
file = FindFiles("C:\TestFolder", "fuel")
If (file <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Sheell Command And Get Output
Dim files As String
Dim lines
files = CreateObject("Wscript.Shell").Exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
lines = Split(files, vbCrLf)
' Look for matching files
Dim curFile As String
Dim line
For Each line In lines
If (Left(line, 11) = "---------- ") Then
curFile = Mid(line, 12)
End If
If (line = target) Then
FindFiles = curFile
Exit Function
End If
Next
FindFiles = ""
End Function
Uses the FIND command line and then reads the output (hence needing to use Wscript.Shell) and returns first match, or empty string if no file is found
Following #BLUEPIXY's command FINDSTR /M the function can be replaced by:
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
End Function

Excel macro to read input from files created today only

I have an application that exports daily reports in txt format.
I have a macro that extracts certain lines of data from those reports and puts them in an output xls file. my macro's input directory is curently a separate folder that i manually move today's reports into.
I'd like for my macro to be able to just read from the default report folder and only read files created with today's date.
the naming convention of the report files is as follows:
1101_16_16_AppServiceUser_YYYYMMDDhhmmssXXX.txt
not sure what the last 3 digits on the file name represents, but they're always numbers.
Help?
WOW that was fast! thanks... fist time using stackoverflow.
I guess i should include the code that pulls data and dumps it to excel... here it is:
Sub PullLinesFromEPremisReport()
Dim FileName, PathN, InputLn As String
Dim SearchFor1, SearchFor2, OutpFile As String
Dim StringLen1, StringLen2 As Integer
Dim colFiles As New Collection
Dim bridgekey As String
PathO = "C:\Documents and Settings\GROMERO\Desktop\CM reconciliation\output\"
PathN = "C:\Documents and Settings\GROMERO\Desktop\CM reconciliation\input\"
FileName = Dir(PathN)
While FileName <> ""
colFiles.Add (FileName)
FileName = Dir
Wend
SearchFor1 = "BRIDGE KEY"
StringLen1 = Len(SearchFor1)
OutpFile = "RESULTS.xls"
Open PathO & OutpFile For Output As #2
For Each Item In colFiles
Open PathN & Item For Input As #1
Do Until EOF(1) = True
Line Input #1, InputLn
If (Left(LTrim$(InputLn), StringLen1) = SearchFor1) Then
bridgekey = InputLn
End If
Loop
Close #1
Next Item
Close #2
End Sub
Daniel's answer is correct, but using the FileSystemObject requires a couple of steps:
Make sure you have a reference to "Microsoft Scripting Runtime":
Then, to iterate through the files in the directory:
Sub WorkOnTodaysReports()
'the vars you'll need
Dim fso As New FileSystemObject
Dim fldr As Folder
Dim fls As Files
Dim fl As File
Set fldr = fso.GetFolder("C:\Reports")
Set fls = fldr.Files
For Each fl In fls
'InStr returns the position of the substring, or 0 if not found
' EDIT: you can explicitly use the reliable parts of your file name
' to avoid false positives
If InStr(1, fl.Name, "AppServiceUser_" & Format(Now, "YYYYMMDD")) > 0 Then
'Do your processing
End If
Next fl
End Sub
EDIT: So I think, from the code you posted, you could send PathN to the main Reports folder like you desire, then just modify your While statement like so:
While FileName <> ""
If InStr(1, FileName, "AppServiceUser_" & Format(Now, "YYYYMMDD")) > 0 Then
colFiles.Add (FileName)
End If
FileName = Dir
Wend
Two ways you can do this off the top of my head. Assuming you are using a File via the FileSystemObject.
Do an Instr on the file.Name looking for Format(Date, "YYYYMMDD") within the string.
Or use a far simpler approach loop through the files and within your loop do this:
If File.DateCreate >= Date Then
'Do something
end if
Where File is the actual variable used to for looping through the files.
If fileName like "*AppServiceUser_" & Format(Now, "YYYYMMDD") & _
"#########.txt" Then
'good to go
End If