I have a workbook with Excel workbook file paths and file names in a column:
C:\D\Folder1\File1.xls
C:\D\Folder2\File2.xls
C:\D\Folder3\File3.xls
Each file and its file path is pulled from a directory like above.
Each of these workbooks contains an email address in cell C15 which I want to copy and paste into the adjacent cell of my workbook like so:
C:D\\Folder1\File1.xls [email protected]
C:\D\Folder2\File2.xls [email protected]
C:\D\Folder3\File3.xls [email protected]
My code only checks one workbook and grabs one email address in cell D17:
C:\D\Folder1\File1.xls [email protected]
C:\D\Folder2\File2.xls
C:\D\Folder3\File3.xls
How can I loop through each workbook in my list.
Here is my code:
Sub SO()
Dim parentFolder As String
parentFolder = Range("F11").Value & "\" '// change as required, keep trailing slash
Dim results As String
results = CreateObject("WScript.Shell").Exec("CMD /C DIR """ & parentFolder & "*.*"" /S /B /A:-D").StdOut.ReadAll
Debug.Print results
'// uncomment to dump results into column A of spreadsheet instead:
Range("D17").Resize(UBound(Split(results, vbCrLf)), 1).Value = WorksheetFunction.Transpose(Split(results, vbCrLf))
Range("Z17").Resize(UBound(Split(results, vbCrLf)), 1).Value = "Remove"
'//-----------------------------------------------------------------
'// uncomment to filter certain files from results.
'// Const filterType As String = "*.exe"
'// Dim filterResults As String
'//
'// filterResults = Join(Filter(Split(results, vbCrLf), filterType), vbCrLf)
'//
'// Debug.Print filterResults
On Error GoTo errHandler
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim app As New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(Range("D17").Value)
Set y = ThisWorkbook
'Now, copy what you want from x:
x.Worksheets(1).Range("C15").Copy
'Now, paste to y worksheet:
y.Worksheets(1).Range("U17").PasteSpecial xlPasteValues
'Close x:
x.Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
errHandler:
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
End Sub