Read .txt from .zip files - excel

I need to open a few .zip files, view a specific .txt and write what's inside of this .txt file to an Excel workbook, and the name of the .zip will be in the same row in Excel.
Example:
The first row is the name of the .zip file and in the first row and second column will be the content of the .txt file.
I have part of the code. It says code error 91.
Sub Text()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Dim I As Long
Dim num As Long
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=True)
If IsArray(Fname) = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
For Each fileNameInZip In oApp.Namespace(Fname).Items
If LCase(fileNameInZip) Like LCase("md5.txt") Then
'Open "md5.txt" For Input As #1
'Do Until EOF(1)
'Line Input #1, textline
' text = text & textline
' Loop
' Close #1
' Range("B1").Value = Mid(text, 1, 32)
' Range("A1").Value = Dir(Fname)
End If
Next
End If
End Sub
I tried to make a loop to open every file md5.txt in every zip that I have to open and take what's inside of the md5.txt

Here is an example of looping through your cells and getting the zip file, extracting the contents, and reading the file. You may need to adjust the path to the zip file or it will default to what ever file the excel document is started in. If you put the whole path to the zip in column A then you would not need to make an adjustment.
Edit was made to reflect the name of the file md5.txt and place contents in second column.
Sub GetData()
Dim iRow As Integer 'row counter
Dim iCol As Integer 'column counter
Dim savePath As String 'place to save the extracted files
Dim fileContents As String 'contents of the file
Dim fso As FileSystemObject 'FileSystemObject to work with files
iRow = 1 'start at first row
iCol = 1 'start at frist column
'set the save path to the temp folder
savePath = Environ("TEMP")
'create the filesystem object
Set fso = New FileSystemObject
Do While ActiveSheet.Cells(iRow, iCol).Value <> ""
fileContents = fso.OpenTextFile(UnzipFile(savePath, ActiveSheet.Cells(iRow, iCol).Value, "md5.txt"), ForReading).ReadAll
ActiveSheet.Cells(iRow, iCol + 1).Value = fileContents
iRow = iRow + 1
Loop
'free the memory
Set fso = Nothing
End Sub
Function UnzipFile(savePath As String, zipName As String, fileName As String) As String
Dim oApp As Shell
Dim strFile As String
'get a shell object
Set oApp = CreateObject("Shell.Application")
'check to see if the zip contains items
If oApp.Namespace(zipName).Items.Count > 0 Then
Dim i As Integer
'loop through all the items in the zip file
For i = 0 To oApp.Namespace(zipName).Items.Count - 1
'check to see if it is the txt file
If UCase(oApp.Namespace(zipName).Items.Item(i)) = UCase(filename) Then
'save the files to the new location
oApp.Namespace(savePath).CopyHere oApp.Namespace(zipName).Items.Item(i)
'set the location of the file
UnzipFile = savePath & "\" & fileName
'exit the function
Exit Function
End If
Next i
End If
'free memory
Set oApp = Nothing
End Function

Related

Select, copy, delete multiple files and create a word document table of content with hyperlink files

I have a listbox (listbox1), I want to select multiple files and copy those files to another folder (Destination folder). Then the listbox will show the data such as file name and filepath of all selected files in the Destination folder.
In Listbox I can choose files and delete them in the Destination folder.
The way i do so far: I save the file path in workbook's cell and add them in listbox. Then try to copy those files from their path saved in cell to Destination folder but it didn't work
The code i use:
Dim FSO
'Create Object Set FSO = CreateObject("Scripting.FileSystemObject")
Dim sSFolder As String
Dim sDFolder As String
Dim sFile, oFile, sh As Worksheet, K&
Set sh = Sheet2
sh.Range("A:A").ClearContents
sFile = Application.GetOpenFilename(Title:="Select files", MultiSelect:=True)
If VarType(sFile) = vbBoolean Then MsgBox ("No file selected"): Exit Sub
For Each oFile In sFile
K = K + 1
sh.Cells(K, 1).Value = oFile
Next
'Change to match the source folder path
sSFolder = oFile
'Change to match the destination folder path
sDFolder = "E:\" & Sheet2.Range("B1").Value & "\" & Sheet2.Range("B2").Value
sFile.CopyFile sSFolder, sDFolder, True
End Sub
Finally, create a word file with Destination folder name and filename with hyperlink (filepath), like this:
Thanks for reading and sorry for my bad english
Here is code i'm trying to create word file
Option Explicit
Sub InsertHyperLink()
Dim aWord As Object
Dim wDoc As Object
Dim i&, EndR&
Dim Rng As Range
Set aWord = CreateObject("Word.Application")
Set wDoc = aWord.Documents.Add
EndR = Range("A65536").End(xlUp).Row
For i = 2 To EndR
wDoc.Range.InsertAfter Cells(i, 1) & vbCrLf
wDoc.Range.InsertAfter vbCrLf
wDoc.Paragraphs(wDoc.Paragraphs.Count).Range.Hyperlinks.Add Anchor:=wDoc.Paragraphs(wDoc.Paragraphs.Count).Range, _
Address:=Cells(i, 3), TextToDisplay:=Left(Cells(i, 2), InStr(1, Cells(i, 2), ".") - 1)
wDoc.Range.InsertAfter vbCrLf
wDoc.Range.InsertAfter vbCrLf
Next
aWord.Visible = True
aWord.Activate
Set wDoc = Nothing
Set aWord = Nothing
End Sub
But with this code, the file in the same folder is not with Folder name:
Folder 1
File 1
Folder 2
File 2....
Folder 1
File 5

How to find cell value in file names in a folder and open that file? File name contains more characters than cell value

This is the first week I learn vba so bear with me if I have a lot of questions;-)
So I have two folders, one folder contains the templates I need to update, the other contains the reports that the updates will be copied from. Cell A1 in each template contains the code that is specific to that BU. I need vba to find the code in the file names in the report folder and open that report. The problem is that the report names have different lengths, eg. it's named as XXX region_code_XXXXXXXXXXX, there can be any number of "X" before and after the code.
Sub Macro1()
Set fso = CreateObject("scripting.filesystemobject")
Set ff = fso.getfolder("C:\Users\35264\summary\test")
For Each file In ff.Files
Workbooks.Openfile
Set wbk2 = ActiveWorkbook
Sheets("Summary").Select
Range("A1").Select
rngX = Range("A1").Value
Now I need to find rngX in the file names in the report folder... I can't figure out how. Let me know if anyone can help! Thank you!
I am learning how to use dir function. I think it will be helpful to get the names of the reports first.
Combine the FileSystemObject Object With the Dir Function
Dir cannot be used in nested Do...Loops.
Using the FileSystemObject object, it opens files in one folder and uses the information in it to open specific files in another folder by using the Dir function. For each combination, it prints their names to the immediate window and closes each file without saving changes.
A better way to do this would be to write the file paths of the first folder to an array by using the Dir function and then loop through the elements of the array to open each file... etc.
Option Explicit
Sub PrintTemplatesAndReports()
' Templates
Const tFolderPath As String = "C:\Users\35264\summary\templates\"
Const tWorksheetName As String = "Summary"
Const rFilePatternAddress As String = "A1"
Const tFileExtensionLeft As String = "xls"
' Reports
Const rFolderPath As String = "C:\Users\35264\summary\reports\"
Const rFileExtensionPattern As String = ".xls*"
' 1st Worbook (ThisWorkbook)
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(tFolderPath) Then Exit Sub
If Not fso.FolderExists(rFolderPath) Then Exit Sub
Dim fsoFolder As Object: Set fsoFolder = fso.Getfolder(tFolderPath)
' Templates (using the FileSystemObject object)
Dim fsoFile As Object
Dim twb As Workbook, tws As Worksheet
Dim tExtension As String, tFilePath As String
' Report (using Dir)
Dim rwb As Workbook
Dim rFilePattern As String, rFileName As String, rFilePath As String
' Counters
Dim ttCount As Long, tCount As Long, rCount As Long
For Each fsoFile In fsoFolder.Files
ttCount = ttCount + 1
tExtension = fso.GetExtensionName(fsoFile)
If InStr(1, tExtension, tFileExtensionLeft, vbTextCompare) = 1 Then
tCount = tCount + 1
tFilePath = tFolderPath & fsoFile.Name
' 2nd Workbook (Template)
Set twb = Workbooks.Open(tFilePath)
On Error Resume Next
Set tws = twb.Worksheets(tWorksheetName)
On Error GoTo 0
If Not tws Is Nothing Then
rFilePattern = CStr(tws.Range(rFilePatternAddress).Value)
rFileName = Dir(rFolderPath, "*" & rFilePattern _
& "*" & rFileExtensionPattern)
Do Until Len(rFileName) = 0
rCount = rCount + 1
rFilePath = rFolderPath & rFileName
' 3rd Workbook (Report)
Set rwb = Workbooks.Open(rFolderPath, rFileName)
' Do your thing, e.g.:
Debug.Print twb.Name, rwb.Name
rwb.Close SaveChanges:=False
rFileName = Dir ' next report
Loop
Set tws = Nothing
End If
twb.Close SaveChanges:=False
End If
Next fsoFile ' next template
MsgBox "Template files processed: " & tCount & "(" & ttCount & ")" _
& vbLf & "Report files processed: " & rCount & "(" & tCount & ")", _
vbInformation
End Sub

VBA "object Variable or With block variable not set" with Shell application

I am trying to extract some data from a series of zip files and store them in the same sheet I'm working on. I have already extract name of each zip file and store them in one column of the sheet. I want to loop through them to extract data I need, however, I keep getting error of "run time error 91" when I access the oApp.Namespace(zipName).Items. Here is the VBA code I have, can anyone help me with that? Thanks!
Sub GetData()
Dim iRow As Integer 'row counter
Dim iCol As Integer 'column counter
Dim savePath As String 'place to save the extracted files
Dim fileContents As String 'contents of the file
Dim fso As FileSystemObject 'FileSystemObject to work with files
iRow = 1 'start at first row
iCol = 1 'start at frist column
'set the save path to the temp folder
savePath = Environ("TEMP")
'create the filesystem object
Set fso = New FileSystemObject
Do While ActiveSheet.Cells(iRow, iCol).Value <> ""
fileContents = fso.OpenTextFile(UnzipFile(savePath, ActiveSheet.Cells(iRow, iCol).Value, "Device-1_IR_VR_7-16-2019-2-32-55_PM.pda-iv.txt"), ForReading).ReadAll
ActiveSheet.Cells(iRow, iCol).Value = fileContents
iRow = iRow + 1
Loop
'free the memory
Set fso = Nothing
End Sub
Function UnzipFile(savePath As String, zipName As String, fileName As String) As String
Dim oApp As Shell
Dim strFile As String
'get a shell object
Set oApp = CreateObject("Shell.Application")
'check to see if the zip contains items
'Debug.Print oApp.Namespace(zipName).Items.Count
If Not IsNull(oApp.Namespace(zipName).Items) Then
If oApp.Namespace(zipName).Items.Count > 0 Then
Dim i As Integer
'loop through all the items in the zip file
For i = 0 To oApp.Namespace(zipName).Items.Count - 1
'check to see if it is the txt file
If UCase(oApp.Namespace(zipName).Items.Item(i)) = UCase(fileName) Then
'save the files to the new location
oApp.Namespace(savePath).CopyHere oApp.Namespace(zipName).Items.Item(i)
'set the location of the file
UnzipFile = savePath & "\" & fileName
'exit the function
Exit Function
End If
Next i
End If
End If
'free memory
Set oApp = Nothing
End Function
Swap your variables to Variant if they're going to be passed to Shell:
Sub GetData()
Dim iRow As Long 'row counter
Dim iCol As Long 'column counter
Dim savePath As Variant 'place to save the extracted files
Dim zipName As Variant
Dim txtPath As String
Dim fileContents As String 'contents of the file
Dim fso As FileSystemObject 'FileSystemObject to work with files
iRow = 1 'start at first row
iCol = 1 'start at first column
savePath = Environ("TEMP") 'set the save path to the temp folder
Set fso = New FileSystemObject 'create the filesystem object
Do While ActiveSheet.Cells(iRow, iCol).Value <> ""
zipName = ActiveSheet.Cells(iRow, iCol).Value
txtPath = UnzipFile(savePath, zipName, "Device-1_IR_VR_7-16-2019-2-32-55_PM.pda-iv.txt")
If Len(txtPath) > 0 Then 'if found the file...
fileContents = fso.OpenTextFile(txtPath, ForReading).ReadAll
ActiveSheet.Cells(iRow, iCol).Value = fileContents
End If
iRow = iRow + 1
Loop
End Sub
Function UnzipFile(savePath As Variant, zipName As Variant, fileName As String) As String
Dim oApp As Object, ns As Object, i As Long
Set oApp = CreateObject("Shell.Application") 'get a shell object
Set ns = oApp.Namespace(zipName) 'get the zip namespace
If ns.Items.Count > 0 Then
For i = 0 To ns.Items.Count - 1
'check to see if it is the txt file
If UCase(ns.Items.Item(i)) = UCase(fileName) Then
'save the files to the new location
oApp.Namespace(savePath).CopyHere ns.Items.Item(i)
UnzipFile = savePath & "\" & fileName 'return the location of the file
Exit Function
End If
Next i
End If
End Function

List file names with links in excel

Is there a way to list file names across different directories in an excel sheet, with links (so one can click on the link beside the file name and the file would open)?
I'm ready to write a script, but I don't know of any particular method or command.
I don't want to be typing the whole thing.
I don't care about directory/tree structure, but file link should be present.
There is one directory which contains lots of other folders which contain the files I need to list, mostly *.pdf's.
Any help appreciated. Thanks!
You can use below code to get File name and File path Set main folder to strFolderPath
'Global Declaration for Start Row
Public lngRow As Long
Sub pReadAllFilesInDirectory()
Dim strFolderPath As String
Dim BlnInclude_subfolder As Boolean
'Set Path here
strFolderPath = "C:\"
'set start row
lngRow = 1
'Set this true if you want list of sub-folders as well
BlnInclude_subfolder = True
'---------- Reading of files in folders and sub-folders------
Call ListMyFiles(strFolderPath, BlnInclude_subfolder)
'---------- Reading of files in folders and sub-folders------
End Sub
Sub ListMyFiles(mySourcePath As String, blnIncludeSubfolders As Boolean)
Dim MyObject As Object
Dim mySource As Object
Dim mySubFolder As Object
Dim myfile As Object
Dim iCol As Long
Set MyObject = CreateObject("Scripting.FileSystemObject")
Set mySource = MyObject.GetFolder(mySourcePath)
'Loop in each file in Folder
For Each myfile In mySource.Files
iCol = 1
Sheet1.Cells(lngRow, iCol).Value = myfile.Name 'File Name
iCol = iCol + 1
Sheet1.Cells(lngRow, iCol).Value = myfile.Path 'File Path/Location
lngRow = lngRow + 1
Next
If blnIncludeSubfolders Then
For Each mySubFolder In mySource.SubFolders
Call ListMyFiles(mySubFolder.Path, True)
Next
End If
End Sub
A quick seach yielded this answer I believe you are looking for.
Sub Example1()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("D:\Stuff\Business\Temp")
i = 1
'loops through each file in the directory
For Each objFile In objFolder.Files
'select cell
Range(Cells(i + 1, 1), Cells(i + 1, 1)).Select
'create hyperlink in selected cell
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
objFile.Path, _
TextToDisplay:=objFile.Name
i = i + 1
Next objFile
End Sub

Get original creation time for all excel files in a folder

I need to loop through a folder containing many excel files and extract the file name and creation time to a text file. By creation time, I mean the time the file was originally created rather than the time it was created on my system.
The following code works, but gives me the wrong time. I think FileDateTime is the wrong command, but after an hour of desperate googling I haven't been able to find the correct one.
Thanks in advance for the help!
Sub CheckFileTimes()
Dim StrFile As String
Dim thisBook As String
Dim creationDate As Date
Dim outputText As String
Const ForReading = 1, ForWriting = 2
Dim fso, f
'set up output file
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\TEST.txt", ForWriting, True)
'open folder and loop through
StrFile = Dir("c:\HW\*.xls*")
Do While Len(StrFile) > 0
'get creation date
creationDate = FileDateTime("C:\HW\" & StrFile)
'get filename
thisBook = StrFile
outputText = thisBook & "," & creationDate
'write to output file
f.writeLine outputText
'move to next file in folder
StrFile = Dir
Loop
f.Close
End Sub
You can use DateCreated with the FileSystemObject.
A small tweak to your current code does this
I have tided up the the variables as well
Sub CheckFileTimes()
Dim StrFile As String
Dim StrCDate As Date
Dim fso As Object
Dim f As Object
'set up output file
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpentextFile("C:\TEST.txt", 2, True)
'open folder and loop through
StrFile = Dir("c:\HW\*.xls*")
Do While Len(StrFile) > 0
Set objFile = fso.getfile("c:\HW\" & StrFile)
'get creation date
StrCDate = objFile.datecreated
'write to output file
f.writeLine StrFile & "," & StrCDate
'move to next file in folder
StrFile = Dir
Loop
f.Close
End Sub
Welp, I found the answer. Looks like I wasn't too far off (though I don't think this is anywhere near optimal). Thanks to everyone who took a look at this.
Sub CheckFileTimes3()
Dim StrFile, thisBook, outputText As String
Dim creationDate As Date
Dim fso, f
Dim oFS As Object
Const ForReading = 1, ForWriting = 2
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
'open txt file for storing results
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\TEST.txt", ForWriting, True)
'loop through all files in given folder
StrFile = Dir("c:\HW\*.xls*")
Do While Len(StrFile) > 0
Workbooks.Open Filename:="C:\HW\" & StrFile
creationDate = ActiveWorkbook.BuiltinDocumentProperties("Creation Date")
thisBook = StrFile
outputText = thisBook & "," & creationDate
'MsgBox outputText
f.writeLine outputText
ActiveWorkbook.Close
StrFile = Dir
Loop
f.Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub

Resources