Change(some)Link(s) Name(s) of Active Workbook VBA - excel

So, I renamed and moved some workbooks that are linked together and I need to update their xlExcelLinks on VBA, the thing is, I have a list of the references to update, but I can't figure out how to update only the ones I need and not every reference on the book.
The initial idea was to search for matching strings between a file name and the stored reference's path. Example data:
A2 Cell on Data.xlsx
Change to
I have this guide example code:
Sub Relink()
Dim previousFile, newFile, oldPath, newPath, Macro, altTab As String
'Macro stores the name of the file running the macro and altTab the name of the file to update
Dim ref as xlExcelLink 'Clearly not a type of data but I need something similar
Windows(Macro).activate
For I = 2 To 4
oldPath = Range("L"& I).Value
newPath = Range("M" & I).Value
previousFile = Range("N" & I).Value
newFile = Range("O" & I).Value
Windows(alTab).activate
'Somehow check for every reference avoiding itself
If ref.Address = oldPath & "\" & previousFile Then
ActiveWorkbook.ChangeLink Name:=oldPath & "\" & previousFile, _
NewName:=newPath & "\" & newFile, Type:=xlExcelLinks
End If
Next
End Sub
Note that on some files there could be only 1 update needed from 50ish references.

Try this code:
Sub UpdateLinks()
'Reference to your change list.
'ThisWorkbook is the file containing this code.
Dim ChangeList As Range
Set ChangeList = ThisWorkbook.Worksheets("Sheet2").Range("A2:D4")
'The workbook containing the links to change.
Dim wrkBk As Workbook
Set wrkBk = Workbooks("Test Timesheet.xlsx")
'If workbook isn't open use:
'Set wrkbk = workbooks.Open(<path to workbook>)
'Look at each link in the workbook.
'lnk must be Variant so it can be used in the For Each loop.
Dim lnk As Variant
For Each lnk In wrkBk.LinkSources
Dim OldPath As String
OldPath = Left(lnk, InStrRev(lnk, "\") - 1)
Dim OldFileName As String
OldFileName = Mid(lnk, InStrRev(lnk, "\") + 1, Len(lnk))
'Search for the existing path in first column of ChangeList.
Dim FoundLink As Range
Set FoundLink = ChangeList.Columns(1).Find(OldPath, , xlValues, xlWhole, xlByRows, xlNext)
'If it's not found, then continue to the next link.
'If it is found check that OldName also exists on that line, if it doesn't then continue searching.
If Not FoundLink Is Nothing Then
Dim firstAdd As String
firstAdd = FoundLink.Address
Do
If FoundLink.Offset(, 2) = OldFileName Then
'Found the link we're after so exit the loop.
Dim NewPath As String
NewPath = FoundLink.Offset(, 1)
Dim NewFileName As String
NewFileName = FoundLink.Offset(, 3)
Exit Do
Else
'Continue searching.
Set FoundLink = ChangeList.Columns(1).FindNext(FoundLink)
End If
Loop While firstAdd <> FoundLink.Address
'Make the change.
wrkBk.ChangeLink Name:=OldPath & Application.PathSeparator & OldFileName, _
NewName:=NewPath & Application.PathSeparator & NewFileName
End If
Next lnk
End Sub

Related

How to copy files with similar name into folders?

I am creating an archiving system where I need to sort files into folders.
I create the folders automatically by mentioning the names of folder in an Excel sheet.
Now I need to copy the files with similar names in that respective folder.
E.g. A folder is created with the name "Ashley Davidson". All the files which are in one source folder and whose file name starts with Ashley Davidson should be copied to this folder.
There will be more than 500 folders and more than 10,000 files to be copied in these folders every week.
The code below creates the folders.
How can I copy the files based on similar name to these folders?
Important
The names of folders will be constant.
The start of the names of files will be similar but users add other words like date, age, sheet 1, sheet 2 etc., therefore List of Partial name concept will probably work here.
Examples of folder names
Example of file names
Code to create folders:
Sub MakeFolders()
Dim sh As Worksheet, lastR As Long, arr, i As Long, rootPath As String
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
arr = sh.Range("A2:A" & lastR).Value2
rootPath = ThisWorkbook.Path & "\"
For i = 1 To UBound(arr)
If arr(i, 1) <> "" And noIllegalChars(CStr(arr(i, 1))) Then
If Dir(rootPath & arr(i, 1), vbDirectory) = "" Then
MkDir rootPath & arr(i, 1)
End If
Else
MsgBox "Illegals characters or empty cell (" & sh.Range("A" & i + 1).Address & ")..."
End If
Next i
End Sub
Function noIllegalChars(x As String) As Boolean
Const illCh As String = "*[\/\\"":\*?]*"
If Not x Like illCh Then noIllegalChars = True
End Function
You did not answer the clarification question and I need to leave my office. The next code assumes that all files exist in a common folder and they should be moved in the folder exactly named as the string in column A:A of the active sheet. It is able to move or copy the file, according to the line you should uncomment:
Sub moveMatchedFilesInAppropriateFolders()
Dim sh As Worksheet, lastR As Long, filesPath As String, fileName As String, foldersRoot As String, folderPath As String
Dim arr, boolNotFound As Boolean, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
arr = sh.Range("A2:A" & lastR).Value2
foldersRoot = ThisWorkbook.Path & "\" 'use here the root folder for folders
filesPath = "your files to be processed folder" 'use here the path where the files can be found
Set fso = CreateObject("Scripting.FileSystemObject") 'to check if file exists
For i = 1 To UBound(arr)
boolNotFound = False
If Dir(foldersRoot & arr(i, 1), vbDirectory) <> "" Then
folderPath = foldersRoot & arr(i, 1) & "\"
Else
MsgBox arr(i, 1) & " folder could not be found!" & vbCrLf & _
"Please, note and correct it after copying the matching ones and run the code again!"
boolNotFound = True
End If
If Not boolNotFound Then
fileName = Dir(filesPath & arr(i, 1) & "*.*")
Do While fileName <> ""
If Not fso.FileExists(folderPath & fileName) Then 'move/copy only if it does not exist in destination fld
'uncomment the way you need (moving or copying):
'Name filesPath & fileName As folderPath & fileName 'the file is moved
'FileCopy filesPath & fileName, folderPath & fileName 'the file is copied
End If
fileName = Dir
Loop
End If
Next i
End Sub
Not tested, but it should work.
If you need something else, please better answer my last clarifications question.
Besides all that, I think it would be good to place a marker in B:B column, for not found folders, if any. In this way, the code can be adapted that at the next run to only run the ones having the marker (and delete it, if the string has been corrected and the folder has been found).
My code works from having the new Folders in the same folder as the workbook you've created said folders from (as it is in your code) and the files to be copied were in a seperate folder in the same path as your workbook; I found that easier to work with since then the only files in that folder are files to be copied, not extra folders within.
Sub copyFilesToFolder()
Dim lRow As Long
Dim wb As Workbook
Dim ws As Worksheet
Dim ccell As Range
Dim fsO As Object, oFolder As Object, oFile As Object
Dim pathFiles As String, sFolderPath As String, sSource As String, sDestination As String
Set wb = ActiveWorkbook
Set ws = wb.ActiveWorksheet
lRow = Range("A" & Rows.Count).End(xlUp).Row
pathFiles = "Q:\WHERE YOUR ORIGINAL WORKBOOK IS\Test\" 'could be gotten from wb technically
Set fsO = CreateObject("Scripting.FileSystemObject")
Set oFolder = fsO.GetFolder(pathFiles)
For Each oFile In oFolder.Files 'go through all the files
For Each ccell In Range("A2:A" & lRow).Cells 'go through all the folder-names
'Debug.Print ccell.Value2
'Debug.Print oFile.Name
If InStr(oFile.Name, ccell.Value2) > 0 Then 'if folder name is in file name
sFolderPath = wb.Path & "\" & ccell.Value2 & "\"
If Dir(sFolderPath, vbDirectory) <> "" Then 'if Folder exists
sDestination = sFolderPath & oFile.Name
If Dir(sDestination) = "" Then 'file doesn't exist yet
sSource = pathFiles & oFile.Name
'Debug.Print sSource
'Debug.Print sDestination
Call fsO.CopyFile(pathFiles & oFile.Name, sFolderPath & oFile.Name)
GoTo Skip
End If
Else
MsgBox ("Folder " & ccell.Value2 & " doesn't exist yet")
End If
End If
Next ccell
Skip:
Next oFile
End Sub
Hope this helps :)

Copying cells from multiple files in 1 folder based on partial file name

I made a post Copying cells from multiple files in one folder.
This answer was correct however I need to change it.
The code from this:
Sub Macro()
Dim StrFile As String, TargetWb As Workbook, ws As Worksheet, i As Long, StrFormula As String
Const strPath As String = "\\pco.X.com\Y\OPERATIONS\X\SharedDocuments\Regulatory\Z\X\" 'take care of the ending backslash
Set TargetWb = Workbooks("X.xlsm")
Set ws = TargetWb.Sheets("Macro")
i = 3
StrFile = Dir(strPath & "*.xls*") 'it returns all files having extensions as xls, xlsx, xlsm, xlsa, xlsb
Dim sheetName As String: sheetName = "S"
Do While Len(StrFile) > 0
StrFormula = "'" & strPath & "[" & StrFile & "]" & sheetName
ws.Range("B" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R24C3")
ws.Range("A" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R3C2")
i = i + 1
StrFile = Dir() 'needed to continue the iteration up to the last file
Loop
End Sub
In the folder where I pull the two data points from there are over 1000 workbooks. I only need the data from around 20/30 of these.
I was planning on getting all the data from this folder and then doing a quick play around to get to the stuff I need. The macro to pull from these 1000 docs is causing Excel to crash.
Is it possible to only pull the data from these files if part of the file name matches with a list of codes in the master sheet?
For example, in column B there are 20 codes listed "3333", "44444" , "562872" etc. and the only files I want are "ABCD 3333 BDBD", "AJKP 4444" and "hhhhh 562872 ha".
Using the function InStr() and an array could do the trick:
Sub Macro()
Dim StrFile As String, TargetWb As Workbook, ws As Worksheet, i As Long, StrFormula As String
Const strPath As String = "\\pco.X.com\Y\OPERATIONS\X\SharedDocuments\Regulatory\Z\X\" 'take care of the ending backslash
'this is the range where the filename codes are. Change as needed
Dim arr_files As Variant: arr_files = ThisWorkbook.Sheets("Master").Range("B2:B20")
Set TargetWb = Workbooks("X.xlsm")
Set ws = TargetWb.Sheets("Macro")
i = 3
StrFile = Dir(strPath & "*.xls*") 'it returns all files having extensions as xls, xlsx, xlsm, xlsa, xlsb
Dim sheetName As String: sheetName = "S"
Do While Len(StrFile) > 0
If Not file_to_process(StrFile, arr_files) Then GoTo skip_file
StrFormula = "'" & strPath & "[" & StrFile & "]" & sheetName
ws.Range("B" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R24C3")
ws.Range("A" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R3C2")
i = i + 1
skip_file:
StrFile = Dir() 'needed to continue the iteration up to the last file
Loop
End Sub
Private Function file_to_process(file_name As String, arr_files As Variant) As Boolean
Dim Key As Variant
For Each Key In arr_files
If InStr(1, file_name, Key, vbTextCompare) > 0 Then
file_to_process = True
Exit For
End If
Next Key
End Function
I've created a little function to check every filename for every code in the arr_files so if one filename has a code in the string, will check as true and get the data.

ExcelVBA: SaveCopyAs won't allow edits to new Workbook

I'm attempting to create code that allows me to edit a workbook, create multiple copies, then edit those copies and save them. I'm hoping someone can talk me through the logic here because I've tried everything I can think of more than once.
Sub RemoveViolations()
Dim fBook As Workbook
Dim fBook2 As Workbook
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
fName = ActiveWorkbook.Name
fSheet = ActiveSheet.Name
fPath = ActiveWorkbook.Path
Set fBook = ActiveWorkbook
For Each c In ActiveSheet.Range("B4:B" & LastRow)
c = UCase(Trim(c.Value))
fName2 = Replace(fName, "swpaSumRPT-", "swpaSumRPT-" & c & "-")
fBook.ActiveSheet.Range("A3:L3").AutoFilter , field:=2, Criteria1:="<>" & c, Operator:=xlFilterValues
If fBook2 Is Nothing Then fBook.SaveCopyAs fPath & "\" & fName2
Set fBook2 = Application.Workbooks.Open(fPath & "\" & fName2)
MsgBox (ActiveWorkbook.Name)
Next c
End Sub
I'm not sure why I can't keep running the code from the original document after the new copy workbook is opened and activated. I've seen examples of others doing this and I THOUGHT I had properly followed the instructions. It appears that once the new workbook is open, the code stops running. I'm hoping you can help me understand.
I'm not toatlly sure what you want to do, but you can try the code below.
If you have more than one workbook open and you want to save all the workbooks, if you want to save all open workbooks, you can use the code below:
Sub SaveAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
wb.Save
Next wb
End Sub
Notice the Dim wb As Workbook. You should specifically reference all objects. Also, make sure everything is managed in the same instance of Excel that you are working with. As I know, a new instance of Excel can't 'see' a current instance of Excel. Check out the ink below when you have some free time.
https://trumpexcel.com/vba-workbook/
Try this adapted code, please:
Sub RemoveViolations()
Dim fBook As Workbook, fBook2 As Workbook, lastRow As Long, fName As String, strC As String
Dim c As Range, fSheet As String, fPath As String, fName2 As String, justName As String
lastRow = ActiveSheet.cells(ActiveSheet.Rows.count, "A").End(xlUp).row
fName = ActiveWorkbook.name
fSheet = ActiveSheet.name
fPath = ActiveWorkbook.Path
Set fBook = ActiveWorkbook
For Each c In ActiveSheet.Range("B4:B" & lastRow)
strC = UCase(Trim(c.Value))
'________________________________________________________________________
justName = Split(fName, ".")(0)
fName2 = Replace(justName, "swpaSumRPT-", "swpaSumRPT-" & strC & "-")
fName2 = fName2 & "." & Split(fName, ".")(1)
'________________________________________________________________________
fBook.ActiveSheet.Range("A3:L3").AutoFilter , field:=2, Criteria1:="<>" & c.value, Operator:=xlFilterValues
If fBook2 Is Nothing Then fBook.SaveCopyAs fPath & "\" & fName2
Set fBook2 = Application.Workbooks.Open(fPath & "\" & fName2)
MsgBox (ActiveWorkbook.name)
Set fBook2 = Nothing
Next c
End Sub
Take 2 steps, copy the files and then open them. This avoids changing the active workbook inside your loop.
Option Explicit
Sub RemoveViolations()
Dim fbook As Workbook, fbook2 As Workbook, ws As Worksheet
Dim c As Range, lastRow As Long
Dim fname As String, fname2 As String
Dim fpath As String, s As String
Dim copies As New Collection
Set fbook = ActiveWorkbook
Set ws = fbook.ActiveSheet
fname = fbook.Name
fpath = fbook.Path
lastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row
' make copies and store name in a collection
For Each c In ws.Range("B4:B" & lastRow)
s = UCase(Trim(c.Value))
fname2 = Replace(fname, "swpaSumRPT-", "swpaSumRPT-" & s & "-")
'Debug.Print s, fname2
ws.Range("A3:L3").AutoFilter , field:=2, Criteria1:="<>" & c, Operator:=xlFilterValues
fbook.SaveCopyAs fpath & "\" & fname2
copies.Add fname2
Next c
ws.Range("A3:L3").AutoFilter ' remove
' open workbooks and delete visible rows
If MsgBox(copies.Count & " copies made. Do you want to open/edit them all ?", vbYesNo, "Confirm Open") = vbYes Then
Dim obj, rng As Range
For Each obj In copies
Set fbook2 = Application.Workbooks.Open(fpath & "\" & obj)
' avoid header 3 rows
Set rng = fbook2.ActiveSheet.UsedRange.Offset(3)
' delete visible rows
rng.SpecialCells(xlCellTypeVisible).EntireRow.Delete
fbook2.ActiveSheet.Range("A3:L3").AutoFilter ' remove filter
Next
End If
End Sub

Scan multiple files and format and copy to master file in VBA or Powerquery

I have some folders with hundreds of reports - all reports are the same, and there´s nothing else in that folders.
I should take multiple workbooks like the first one in the image, and recopilate them in a master file (second image).
I have some code - below - but I don´t know how to complete it; The workbook is a template, so it always have 15 rows (could be completed or not) and I need to bring all that´s there plus the date and group control, which is shared by every document inside the file.
I´d appreciate if you could help me complete the code; somebody told me this could be done using powerquery but I´ve never used it. If you think this would be easier, please let me know your thoughts.
Thanks!!
What I have:
Public Sub test()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Path = "C:\Users\Maudibe\Desktop\ExcelFiles\"
Filename = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
'
' **WHAT TO DO HERE?**
'
MsgBox Filename & " has opened"
wbk.Close True
Filename = Dir
Loop
End Sub
So i modified your code to this: (Has to be in ThisWorkbook)
Public Sub test()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim sht, msht As Worksheet
Dim lRowFile, lRowMaster As Long
Dim FirstDataSet As Integer
Path = "C:\Users\User\Desktop\Files\"
Filename = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Filename <> "" And Filename <> "Master.xlsm" 'Dont Open MasterFile 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
Set sht = Workbooks(Filename).Worksheets(1) 'First Sheet in File
Set msht = ThisWorkbook.Worksheets(1) 'First Sheet in Master
lRF = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'Last Row in File
lRM = msht.Cells(Rows.Count, 1).End(xlUp).Row 'Last Row in Master
FirstDataSet = 5 'First Data Set in File
For i = FirstDataSet To lRF
lRM = msht.Cells(Rows.Count, 1).End(xlUp).Row 'Last Row in Master
msht.Range("A" & lRM + 1).Value = sht.Range("A" & i).Value 'DocumentName
msht.Range("B" & lRM + 1).Value = sht.Range("B" & i).Value 'Amount
msht.Range("C" & lRM + 1).Value = sht.Range("D2").Value 'Date
msht.Range("D" & lRM + 1).Value = sht.Range("D3").Value 'Group #
Next i
wbk.Close True
Filename = Dir
Loop
End Sub
It will open the workbooks and check which rows are filled in Col A (Non used have to be blank). Then it copies the Data to the Master File. My Workbooks that have been opened looked like this and the Result:

Excel VBA Search in folder and subfolders and returns multiple files

I have to search and copy a number of files in a folder starting from an Excel list like:
8100 ' cell "A2"
8152 ' cell "A3"
8153 ' cell "A4"
in the source folders there are files named like this:
8153.pdf
100_8152.pdf
102_8153.pdf
8153 (2).pdf
How can I find these files and copy ALL the files that matches in a separate folder? The code returns only one file, but I need ALL the files matching the cell value. I need to extend my research in subfolders organized by years too (ie: "D:\myfolder\2015", "D:\myfolder\2016", etc.).
Thanks to user3598756, I'm now using this code:
Option Explicit
Sub cerca()
Dim T As Variant
Dim D As Variant
T = VBA.Format(VBA.Time, "hh.mm.ss")
D = VBA.Format(VBA.Date, "yyyy.MM.dd")
Dim Source As String
Dim Dest As String
Dim Missed As String
Dim fileFound As String
Dim CodiceCS As Variant
Dim cell As Range
Source = "D:\myfolder\"
Dest = "D:\myfolder\research " & D & " " & T
If Dir(Dest, vbDirectory) = "" Then MkDir Dest '<--| create destination folder if not alerady there
With Worksheets("Cerca") '<-- reference your worksheet with pdf names
For Each cell In .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- loop through its column "A" cells with "constant" (i.e. not resulting from formulas) values from row 2 down to last non empty one
CodiceCS = VBA.Left((cell.Value), 4)
fileFound = Dir(Source & "\" & CodiceCS & "\*" & cell.Value & "*.Pdf") '<-- look for a source folder file whose name contains the current cell value
If fileFound <> "" Then '<-- if found...
FileCopy Source & "\" & CodiceCS & "\" & fileFound, Dest & "\" & fileFound '<-- ...copy to destination folder
Else '<--otherwise...
Missed = Missed & cell.Value & vbCrLf '<--... update missing files list
End If
Next cell
End With
If Missed <> "" Then '<-- if there's any missing file
Dim FF As Long
FF = FreeFile
Open (Dest & "\" & "MissingFiles.txt") For Output As #FF
Write #FF, VBA.Left(Missed, Len(Missed) - 2)
Close #FF
End If
MsgBox "OK"
Shell "explorer.exe " + Dest, vbNormalFocus
End Sub
This code will place all the file names in the main folder and subfolders into an array. It then looks through the array for matching values.
I've included an extra couple of lines which I've commented out - these are different options you could do within the code.
Public Sub cerca()
Dim DT As String
Dim Source As String
Dim Dest As String
Dim vFiles As Variant
Dim vFile As Variant
Dim rCell As Range
Dim oFSO As Object
Dim FileFound As Boolean
Dim FF As Long
FF = FreeFile
DT = Format(Now, "yyyy.mm.dd hh.mm.ss")
Set oFSO = CreateObject("Scripting.FileSystemObject")
Source = "D:\myfolder\"
Dest = "D:\myfolder\research " & DT
If Dir(Dest, vbDirectory) = "" Then MkDir Dest
'Get the full path name of all PDF files in the source folder and subfolders.
vFiles = EnumerateFiles(Source, "pdf")
With Worksheets("Cerca")
'Look at each cell containing file names.
For Each rCell In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
FileFound = False 'Assume the file hasn't been found.
'Check each value in the array of files.
For Each vFile In vFiles
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Use this line if the file name in the sheet exactly match the file name in the array. '
'8152 and 100_8152.pdf are not a match, 8152 and 8152.pdf are a match. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rCell & ".pdf" = FileNameOnly(vFile) Then
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Use this line if the file name in the sheet should appear in the file name in the array. '
'8152 and 100_8152.pdf are a match, 1852 and 8152.pdf are a match. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If InStr(FileNameOnly(vFile), rCell.Value) > 0 Then
'If found copy the file over and indicate it was found.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This line will use the rcell value to name the file. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
oFSO.CopyFile vFile, Dest & "\" & rCell & ".pdf"
''''''''''''''''''''''''''''''''''''''
'This line will not rename the file. '
''''''''''''''''''''''''''''''''''''''
'oFSO.CopyFile vFile, Dest & "\" & FileNameOnly(vFile)
FileFound = True
End If
Next vFile
'Any file names that aren't found are appended to the text file.
If Not FileFound Then
Open (Dest & "\" & "MissingFiles.txt") For Append As #FF ' creates the file if it doesn't exist
Print #FF, rCell ' write information at the end of the text file
Close #FF
End If
Next rCell
End With
End Sub
Public Function EnumerateFiles(sDirectory As String, _
Optional sFileSpec As String = "*", _
Optional InclSubFolders As Boolean = True) As Variant
EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")
End Function
Public Function FileNameOnly(ByVal FileNameAndPath As String) As String
FileNameOnly = Mid(FileNameAndPath, InStrRev(FileNameAndPath, "\") + 1, Len(FileNameAndPath))
End Function

Resources