How can I delete pdf files when sums to zero - excel

I'm trying to see if there is a way to delete a pdf file when the row balances to zero. I tried to follow this but I could not get it to work for me, any help pointing me in the right direction would be greatly appreciated.
Goals
Delete pdf file if Column N5 balances to zero if exists, pdf is named after RGN in A5 usually
Loop through all the rows and until it reaches the end
Bonus would be to account for wildcard naming since sometimes the pdf could be RGN_649610.pdf
Example 649610.pdf should be deleted when N5 balances to 0 as shown in the image.
C:.
│ TES_123.xlsx
│
└───Scanned
├───DIR1
│ 649610.pdf
│ 649615.pdf
│
└───DIR2
649612.pdf
649617.pdf
Excel image
Code I tried
Sub delete_INACTIVE_files()
Const path = "C:\Users\bmh\Desktop\TES 123\"
Dim r As Range
Set r = Cells(5, 14)
Do Until r = ""
If UCase(r.Value) = "0" Then
If Dir(path & "Scanned" & "\DIR1" & "\" & r.Offset(0, -13) & ".pdf") <> "" Then
Kill path & "Scanned" & "\DIR1" & "\" & r.Offset(0, -13) & ".pdf"
End If
End If
Set r = r.Offset(5, 0)
Loop
End Sub

Try this:
Sub delete_INACTIVE_files()
Const PATH = "C:\Users\bmh\Desktop\TES 123\Scanned\"
Dim r As Range, ws As Worksheet, id, n, f, files As Collection, fName
Set files = GetMatches(PATH, "*.pdf") 'find all files in the folder/subfolders
Set ws = ActiveSheet
Set r = ws.Cells(5, 14)
Do While Len(r.Value) > 0
If r.Value = 0 Then
id = ws.Cells(r.Row, "A").Value 'get the Region
'find any matching files and delete them
For n = files.Count To 1 Step -1
Set f = files(n)
fName = UCase(f.Name)
If fName = id & ".PDF" Or _
fName = "RGN_" & id & ".PDF" Then
f.Delete 'delete the file
files.Remove n 'remove from the collection
End If
Next n
End If
Set r = r.Offset(1, 0) 'next row
Loop
End Sub
'Return a collection of file objects given a starting folder and a file pattern
' e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetMatches(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Collection
Dim fso, fldr, f, subFldr
Dim colFiles As New Collection
Dim colSub As New Collection
Set fso = CreateObject("scripting.filesystemobject")
colSub.Add startFolder
Do While colSub.Count > 0
Set fldr = fso.getfolder(colSub(1))
colSub.Remove 1
For Each f In fldr.files
If UCase(f.Name) Like UCase(filePattern) Then colFiles.Add f
Next f
If subFolders Then
For Each subFldr In fldr.subFolders
colSub.Add subFldr.PATH
Next subFldr
End If
Loop
Set GetMatches = colFiles
End Function

Related

How do I find a file with two keywords and return a date modified in a specific column / row?

I'm trying to search a networked drive for files including two keywords. When found, I need them to return the last modified date of said file to the same row one of the keywords was pulled from.
I've found something that is similar to what I need, but it doesn't search for specific keywords.
Sub GetFilesDetails()
' in column G= Date Last Modified
Dim objFSO As Scripting.FileSystemObject
Dim myFolder As Scripting.Folder
Dim myFile As Scripting.File
Dim R as Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set myFolder = objFSO.GetFolder(“S:\”)
Application.ScreenUpdating = False
For Each myFile In myFolder.Files
ThisWorkbook.Sheets("Sheet1").Cells(R, 7).Value = myFile.DateLastModified
R = R + 1
Next myFile
Application.ScreenUpdating = True
MsgBox "Updated"
End Sub
I need keyword 1 to be "Proof" and keyword 2 to be variable based on the column B value. So starting at row 4, Keyword "Proof" and (B4) are the search terms to find the most recent file, and return the last modified date of the file into (G4). From there continue through the rows performing the same task, but skip any row with a blank B cell.
Any help is greatly appreciated!
Edit: The keywords will be in the file name. ie "WO67547_Proof1"
Proof is on all of the files that I will be looking for and the WO# is the variable. As long as the only last modified date pulled is the most recent, there shouldn't be more than one occurrence of the WO# and Proof keywords.
Please, use the next code. It extract the matching file names matching each pair of the two keywords and choose the most recent date. The code should be very fast, using arrays. For processing and returning, too:
Sub GetFilesDetails()
Dim sh As Worksheet, lastR As Long, arrKeys, arrDate, i As Long, fileName As String
Dim folderPath As String, lastModifDate As Date, lastDate As Date
Const key2 As String = "Proof"
Set sh = ActiveSheet 'use here the necessary worksheet
lastR = sh.Range("B" & sh.rows.count).End(xlUp).Row
arrKeys = sh.Range("B4:B" & lastR).Value2 'place the range in an array for faster iteration
arrDate = sh.Range("G4:G" & lastR).Value2
folderPath = "C:/the necessary folder path" 'Use here your real Folder Path!!!
For i = 1 To UBound(arrKeys)
If arrKeys(i, 1) <> "" Then
fileName = Dir(folderPath & "\" & "*" & arrKeys(i, 1) & "*" & key2 & "*.xlsx")
lastDate = 0
Do While fileName <> ""
lastModifDate = CDate(Int(FileDateTime(folderPath & "\" & fileName)))
If lastModifDate > lastDate Then lastDate = lastModifDate
fileName = Dir
Loop
If lastModifDate <> 0 Then arrDate(i, 1) = lastModifDate: lastModifDate = 0
End If
Next i
With sh.Range("G4").Resize(UBound(arrDate), 1)
.Value2 = arrDate
.NumberFormat = "dd-mmm-yy"
End With
End Sub
Do not forget to update folderPath with your real folder where the files to be processed exist.

Excel VBA search subfolders

This is what i got, it works, but it doesn't search the subfolders of "K:". What am i doing wrong?
Sub Search()
Dim RGFileName As String
Dim RGNumber As String
Dim Path As String
Path = "K:\"
RGNumber = InputBox("Input RG-Number (33xxxx)", "RG-Number")
RGFileName = Dir(Path & "*" & RGNumber & "*.xlsm")
If RGFileName <> "" Then
Workbooks.Open Path & RGFileName
End If
End Sub
Using a separate function to perform the search - returns a collection of File objects:
Sub Search()
Dim RGFileName As String
Dim RGNumber As String
Dim Path As String, allFiles As Collection
Path = "K:\"
RGNumber = InputBox("Input RG-Number (33xxxx)", "RG-Number")
Set allFiles = GetMatches(Path, "*" & RGNumber & "*.xlsm")
If allFiles.Count > 0 Then
Workbooks.Open allFiles(1).Path
Else
MsgBox "No match"
End If
End Sub
'Return a collection of file objects given a starting folder and a file pattern
' e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetMatches(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Collection
Dim fso, fldr, f, subFldr
Dim colFiles As New Collection
Dim colSub As New Collection
Set fso = CreateObject("scripting.filesystemobject")
colSub.Add startFolder
Do While colSub.Count > 0
Set fldr = fso.getfolder(colSub(1))
colSub.Remove 1
For Each f In fldr.Files
If UCase(f.Name) Like UCase(filePattern) Then colFiles.Add f
Next f
If subFolders Then
For Each subFldr In fldr.subFolders
colSub.Add subFldr.Path
Next subFldr
End If
Loop
Set GetMatches = colFiles
End Function
Edit: this will look for the first match and return the full path to the file
Function MatchFirstFile(startFolder As String, filePattern As String) As String
Dim colSub As New Collection, f, fld
colSub.Add startFolder
Do While colSub.Count > 0
fld = colSub(1)
colSub.Remove 1
f = Dir(fld, vbDirectory)
Do While Len(f) > 0
If GetAttr(fld & f) = vbDirectory Then
If f <> "." And f <> ".." Then 'ignore parent and current folders
colSub.Add fld & f & "\"
End If
Else
If UCase(f) Like UCase(filePattern) Then
MatchFile = fld & f
Exit Function
End If
End If
f = Dir()
Loop
Loop
End Function

Looking through a folder/subfolders to find and print a list of pdfs

I have a list of pdfs which are located in one folder and subfolders within that folder. I would like to be able to have a macro that goes down the list and prints each of the pdf's after finding them in the folders.
The list of pdf names in the excel sheet start on B3 and go down. The look like "10028844" while the pdf's are saved with the same name "10028844.pdf".
I've looked all around and have found many examples on how to look through folders for ALL files in the folder/subfolder but none that look for specific files or a list of files. Any help is appreciated.
I've found some articles that helped with some code by adding the files to a collection but when I run this macro there is nothing in the collection. Does anyone see where this is going wrong?
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End Sub
.
Sub BatchPrint()
Dim colFiles As New Collection
Dim CustRow, LastRow As Long
LastRow = Sheet1.Range("B9999").End(xlUp).Row
With Sheet1
For CustRow = 3 To LastRow
GetFiles "C:\Users\Desktop\Test\", "B" & CustRow & ".pdf", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
Next CustRow
End With
Dim i As Long
For i = 1 To colFiles.Count
Debug.Print colFiles(i)
Next i
End Sub
After some work I finally got this to work. Code below. Choose what happens to the collection by changing the line Debug.Print colFiles(i).
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End Sub
.
Sub BatchPrint()
Dim colFiles As New Collection
Dim CustRow, LastRow As Long
Set colFiles = New Collection
LastRow = Sheet1.Range("B9999").End(xlUp).Row
With Sheet1
For CustRow = 3 To LastRow
GetFiles "C:\Users\Desktop\Test\", Sheet1.Range("B" & CustRow) & ".pdf", True, colFiles
Next CustRow
End With
Dim i As Long
For i = 1 To colFiles.Count
Debug.Print colFiles(i)
Next i
Set colFiles = Nothing
End Sub

I can't run VBA Macro on all workbooks inside a folder

I just started working with VBA.
I have a VBA code that counts the number of the occurence of words inside the excel file. It works fine.
I want to run this VBA macro on all files I have inside a specific folder.
Could you help me out?
My code below:
I am getting values right only for the file from which I ran the macro. For the rest of the files, the reults obtained are wrong
Sub LoopThroughFiles()
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.xls*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
Dim wordList As New Collection
Dim keyList As New Collection
Dim c
Worksheets("Sheet1").Activate
Dim RangeToCheck As Range
Set RangeToCheck = Range("A1:A1000")
For Each c In RangeToCheck
Dim words As Variant
words = Split(c, " ")
For Each w In words
Dim temp
temp = -1
On Error Resume Next
temp = wordList(w)
On Error GoTo 0
If temp = -1 Then
wordList.Add 1, Key:=w
keyList.Add w, Key:=w
Else
wordList.Remove (w)
keyList.Remove (w)
wordList.Add temp + 1, w
keyList.Add w, Key:=w
End If
Next w
Next c
Dim x
Dim k
k = 1
For x = 1 To wordList.Count
With Sheets("Sheet1")
.Cells(k, "E").Value = keyList(x)
.Cells(k, "F").Value = wordList(x)
k = k + 1
End If
End With
Next x
End With
xFileName = Dir
Loop
End If
End Sub
Try this
Public Sub LoopThroughFiles()
Dim xFd As FileDialog
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
xFd.AllowMultiSelect = False
If xFd.Show <> -1 Then
MsgBox "No Folder selected": Exit Sub
End If
Dim Folder As String: Folder = xFd.SelectedItems(1) & "\"
Dim Files
Files = Dir(Folder & "*.xls*")
Dim Xls As String
On Error Resume Next
Dim CrWB As Workbook, CrSheet As Worksheet
Dim ClnW As New Collection, ClnC As New Collection
Dim Cols As Integer: Cols = 1
Do While Files <> ""
Xls = Replace(Folder & Files, "\\", "\")
Set CrWB = Application.Workbooks.Open(Xls, , True)
Set CrSheet = CrWB.Sheets("Sheet1")
If Err.Number > 0 Then
MsgBox "Can't open File " & Xls & vbCrLf & Err.Description
Err.Clear
GoTo 1
End If
Dim c As Range
Set ClnW = New Collection: Set ClnC = New Collection
For Each c In CrSheet.Range("A1:A1000")
If c.Value <> "" Then
Words = Split(CStr(c.Value), " ", , vbTextCompare)
For Each s In Words
Err.Clear
tmp = ClnW(s)
If Err.Number > 0 Then
ClnW.Add Item:=s, Key:=s
ClnC.Add Item:=1, Key:=s
Else
x = ClnC(s) + 1
ClnC.Remove s
ClnC.Add Item:=x, Key:=s
End If
Next
End If
Next
Set CrSheet = ThisWorkbook.Sheets("Sheet1")
With CrSheet
.Cells(1, Cols).Value = Files
.Cells(2, Cols).Value = "Word"
.Cells(2, Cols + 1).Value = "Occurance"
.Range(.Cells(1, Cols), .Cells(1, Cols + 1)).Merge
Dim I As Integer: I = 3
For Each s In ClnW
.Cells(I, Cols).Value = s
.Cells(I, Cols + 1).Value = ClnC(s)
I = I + 1
Next
End With
Cols = Cols + 2
1
CrWB.Close False
Files = Dir()
Err.Clear
Loop
End Sub

How to copy 100 files to a folder based on first and last file name and display in listbox vba

Im trying to come up with a piece of script that will allow me to copy 100 files from one folder and create a new folder based on the first file and last file name and then move those 100 files to that folder.
After moving those files, i want it to display the folders in a userform listbox as clickable items.
For example, each item in the listbox will be a folder, if i double click on a folders name it will display all the contents of the file (of each of 100 files) in a sheet i've set up.
I haven't been able to test this code yet, all i've done for the past week was research and rewrite the code over and over until i could understand it properly before adding it to the program. So there's bound to be some or more errors along the way.
What i did notice was the "objFile.CopyFile Folderpath & FCount & "_" & LCount" piece of code that doesnt specify which files could be copied specifically. For example, i want it to start at the first file and start coping the first 100 files, when the code is executed again, it will start at file 101 and copy the next 100 files. If there's way to ensure that it wouldnt keep copying the first 100 files, that would be awesome!
Sub Main()
'====CHECK IF THERE'S 100 FILES====
Dim filename, folderpath, path As String
Dim count As Integer
Dim FCount, LCount, FlagCount, IntCount As Integer
Dim objFSO As Object
Dim obj As Object
FCount = 0 ' First File name
LCount = 0 'Last file name
count = 0 'file count
FlagCount = Sheets("Flag Sheet").Range("A2").Value
folderpath = "Work\Big Book\" '==================Location Of The Book
path = folderpath & "*.xls"
filename = Dir(path)
Do While filename <> ""
count = count + 1
filename = Dir(path)
Loop
If count < 100 Then
'====CREATE A FOLDER FOR THE FILES====
If FlagCount <> "" Then '====If there is a flag count, it will create a folder based on the last number it was used
FCount = FlagCount + 1
LCount = FlagCount + 101
MkDir folderpath & FCount & "_" & LCount
Else '=======================else if there isnt one, it will use the first file name to create the folder
FCount = IntCount + 1
LCount = IntCount + 100
MkDir folderpath & FCount & "_" & LCount
End If
'====MOVE 100 FILES TO FOLDER====
For Each objFile In objFSO.GetFolder(path)
If FlagCount <> "" Then '====================if theres a flag count it will move the files starting after the flag count + 101
objFile.CopyFile folderpath & FCount & "_" & LCount
IntCount = FlagCount + 1
If IntCount = FlagCount + 100 Then Exit For
Else '======================================else it will just move the first 100 files
objFile.CopyFile folderpath & FCount & "_" & LCount
IntCount = IntCount + 1
If IntCount = IntCount + 100 Then Exit For
End If
Next
End If
Else
'===Do Nothing===
End If
End Sub
'=====Display Folders In Listbox=====
'====Display Folder Items In Book====
'Call the function
DisplayFoldersInListBox folderpath & FCount & "_" & LCount, Me.Listbox1
Sub Button_Click()
For Each File in Folderpath & FCount & "_" & LCount & "\" & Listbox.value
'[INSERT BIG BOOK CODE]
Next
End Sub
Private Sub DisplayFoldersInListBox(ByVal strRootFolder As String, ByRef lbxDisplay As MSForms.ListBox)
Dim fso As Object
Dim fsoRoot As Object
Dim fsoFolder As Object
'Make sure that root folder contains trailing backslash
If Right$(strRootFolder, 1) <> "\" Then strRootFolder = strRootFolder & "\"
'Get reference to the FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
'Get the root folder
Set fsoRoot = fso.GetFolder(strRootFolder)
'Clear the listbox
lbxDisplay.Clear
'Populate the listbox with subfolders of Root
For Each fsoFolder In fsoRoot.SubFolders
lbxDisplay.AddItem fsoFolder.Name
Next fsoFolder
'Clean up
Set fsoRoot = Nothing
Set fso = Nothing
End Sub
This link: Copy only the first file of a folder VBA
Seems to be the answer for the coping of the files, but im not entirely sure how to add it to my script. Can anyone help me out?
Back to the basics:
CopyXNumberOfFiles:Sub
Sub CopyXNumberOfFiles(SourceFolder As String, TargetFolder As String, Optional MaxNumFiles As Long = 100)
Dim fso As Object, objFile As Object
Dim count As Long
Dim Path As String
Set fso = CreateObject("Scripting.FileSystemObject")
If Not Right(SourceFolder, 1) = "\" Then SourceFolder = SourceFolder & "\"
If Not Right(TargetFolder, 1) = "\" Then TargetFolder = TargetFolder & "\"
For Each objFile In fso.GetFolder(SourceFolder).Files
If objFile.Path Like "*.xls?" Then
Path = TargetFolder & objFile.Name
If Len(Dir(Path)) = 0 Then
FileCopy objFile.Path, Path
count = count + 1
If count >= MaxNumFiles Then Exit For
End If
End If
Next
End Sub
Usage
CopyXNumberOfFiles "C:\","C:\Data"
Addendum
This function will copy the files over and return an array of the new file paths.
Function getCopyXNumberOfFiles(SourceFolder As String, TargetFolder As String, Optional MaxNumFiles As Long = 100) As String()
Dim fso As Object, objFile As Object
Dim count As Long, n As Long
Dim Path As String
Dim data() As String, results() As String
ReDim data(1 To 2, 1 To MaxNumFiles)
Set fso = CreateObject("Scripting.FileSystemObject")
If Not Right(SourceFolder, 1) = "\" Then SourceFolder = SourceFolder & "\"
If Not Right(TargetFolder, 1) = "\" Then TargetFolder = TargetFolder & "\"
For Each objFile In fso.GetFolder(SourceFolder).Files
If objFile.Path Like "*.xls?" Then
Path = TargetFolder & objFile.Name
If Len(Dir(Path)) = 0 Then
FileCopy objFile.Path, Path
count = count + 1
data(1, count) = objFile.Path
data(2, count) = Path
If count >= MaxNumFiles Then Exit For
End If
End If
Next
ReDim Preserve results(1 To count, 1 To 2)
For n = 1 To count
results(n, 1) = data(1, n)
results(n, 2) = data(2, n)
Next
getCopyXNumberOfFiles = results
End Function
Usage
Column 1 has the original paths and column 2 has the new paths.
Dim Files() as String, firstFilePath as String, lastFilePath as String
Files = getCopyXNumberOfFiles("C:\", "C:\New Folder\", 100)
Original Paths
firstFilePath = Files(1, 1)
lastFilePath = Files(Ubound(Files), 1)
New Paths
firstFilePath = Files(1, 2)
lastFilePath = Files(Ubound(Files), 2)

Resources