Query user to choose path - vba

I have a code that reads a folder contents (only other folders) and lists them into excel in a certain range.
The problem is that the path where the code reads contents (/CtrExtrase) is given in the code.
I need the path to be choosen by the user. Tried and failed totally.
My code:
Sub distribuire_foldere()
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim i As Integer
'CLEARS ALL PREVIOUS CONTENT
Sheets("DISTRIBUIRE foldere").Range("A2:A2000").ClearContents
'INSERTS IN CELL THE PATH WHERE THE SCRIPT IS READING
Sheets("DISTRIBUIRE foldere").Range("$E$1").Value = ThisWorkbook.path & "\CtrExtrase"
' LISTS THE CONTENT OF THE CHOOSEN FOLDER
Application.StatusBar = ""
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
On Error GoTo nuexistafolderul
'THIS IS THE PROBLEM, AS I NEED THE USER TO CHOOSE THE PATH:
Set objFolder = objFSO.GetFolder(Application.ThisWorkbook.path & "\CtrExtrase")
i = 1
'loops through each folder in the directory and prints their names
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
For Each objSubFolder In objFolder.subfolders
Application.StatusBar = objSubFolder.path & " " & objSubFolder.Name
'OUTPUTS THE FOLDERS NAME
Cells(i + 1, 1) = objSubFolder.Name
i = i + 1
Next objSubFolder
handleCancel:
If Err = 18 Then
MsgBox "Ai anulat procesul inainte de finalizare! Reia procedura!"
nuexistafolderul:
MsgBox "Nu exista folderul pentru extractia contractelor! Extrage intai contractele!"
End If
'CALLS A MODULE THAT INSERTS CERTAIN TEXT INTO A BATCH FILE
Call Module1.batchfile2
End Sub

Use FileDialog with FolderPicker, here it's wrap in a function :
Function GetFolder(Optional strPath As String = "C:\") As String
Dim fldr As FileDialog
Dim sItem As String
GetFolder = vbNullString
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
And your code, you can set the default path in GetFolder(ThisWorkbook.Path & "\") :
Sub distribuire_foldere()
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim i As Integer
'CLEARS ALL PREVIOUS CONTENT
Sheets("DISTRIBUIRE foldere").Range("A2:A2000").ClearContents
'INSERTS IN CELL THE PATH WHERE THE SCRIPT IS READING
Sheets("DISTRIBUIRE foldere").Range("$E$1").Value = ThisWorkbook.Path & "\CtrExtrase"
' LISTS THE CONTENT OF THE CHOOSEN FOLDER
Application.StatusBar = ""
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
On Error GoTo nuexistafolderul
'THIS IS THE PROBLEM, AS I NEED THE USER TO CHOOSE THE PATH:
Set objFolder = objFSO.GetFolder(GetFolder(ThisWorkbook.Path & "\"))
i = 1
'loops through each folder in the directory and prints their names
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
For Each objSubFolder In objFolder.SubFolders
Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
'OUTPUTS THE FOLDERS NAME
Cells(i + 1, 1) = objSubFolder.Name
i = i + 1
Next objSubFolder
handleCancel:
If Err = 18 Then
MsgBox "Ai anulat procesul inainte de finalizare! Reia procedura!"
nuexistafolderul:
MsgBox "Nu exista folderul pentru extractia contractelor! Extrage intai contractele!"
End If
'CALLS A MODULE THAT INSERTS CERTAIN TEXT INTO A BATCH FILE
Call Module1.batchfile2
End Sub

Related

After finding files, find subsequently received file

This code finds files that have a certain date in the file name, then saves them in a specified folder.
When another file that has the same date comes in, I want to add this file to the collection of previously found files. It doesn't find the new file.
If I delete the previously made folders and run it from scratch it will find all the files. It is like the recursivefilesearch isn't refreshing the folder and just using the previously found files.
Option Explicit
Sub Merge_Data()
Application.StatusBar = "Finding today's files"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim FilePath As String
FilePath = "folder\"
' Ask user what date they would like to merge the files for
Dim dateString As String, TheDate As Date
Dim valid As Boolean: valid = True
Dim Input_Box_Msg As String
Input_Box_Msg = "What Date would you like to merge the files for? " & vbNewLine & "Please enter date in format mm/dd/yyyy: "
Do
dateString = InputBox(Input_Box_Msg)
If IsDate(dateString) Then
TheDate = DateValue(dateString)
valid = True
Else
MsgBox "Invalid date. Please enter date in format mm/dd/yyyy:"
valid = False
End If
Loop Until valid = True
'Edit_1: Based on Comment
' Obtain current date in format yyyymmdd
Dim Current_Date, Current_Date_1 As String
Current_Date = Format(TheDate, "yyyymmdd")
Current_Date_1 = Format(TheDate, "yyyy_mm_dd")
' Find all files in folder that contain previously input date by the user
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objRegExp As Object
Set objRegExp = CreateObject("VBScript.RegExp")
' Regex object with previously input date by the user
objRegExp.Pattern = Current_Date
objRegExp.IgnoreCase = True
Dim colFiles As Collection
Set colFiles = New Collection
Dim f As Variant
' Recursively search through folders for files that match today's date
RecursiveFileSearch FilePath, objRegExp, colFiles, objFSO
Dim Combined_Path As String
Combined_Path = "new_folder\"
Combined_Path = Combined_Path & Current_Date & "\"
Dim Path As String
Dim Folder As String
Dim FileFormatNum As Long
Dim FileName As String
' .xlsx extension number
FileFormatNum = 51
Path = Combined_Path
Folder = Dir(Path, vbDirectory)
' Create New folder to store today's files
If Folder = vbNullString Then
VBA.FileSystem.MkDir (Path)
End If
Dim Full_File_Path As String
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim File_Type_1 As String
Application.StatusBar = "Saving today's files in new folder"
' Save Files that match criteria in new folder in .xlsx format
For Each f In colFiles
Workbooks.Open f
FileName = ActiveWorkbook.Name
MsgBox FileName
File_Type_1 = FSO.GetExtensionName(FileName)
If File_Type_1 = "xls" Then
FileName = FileName & "x"
Full_File_Path = Path & FileName
ActiveWorkbook.SaveAs FileName:=Full_File_Path, FileFormat:=FileFormatNum, CreateBackup:=False
ActiveWorkbook.Close
File_Type_1 = ""
FileName = ""
Full_File_Path = ""
ElseIf File_Type_1 = "xlsx" Then
If Left(FileName, 11) = "Merged_File" Then Exit For
Else
Full_File_Path = Path & FileName
ActiveWorkbook.Close
Kill Full_File_Path
ActiveWorkbook.SaveAs FileName:=Full_File_Path, FileFormat:=FileFormatNum, CreateBackup:=False
ActiveWorkbook.Close
FileName = ""
Full_File_Path = ""
File_Type_1 = ""
End If
Next
FilePath = ""
Current_Date = ""
Current_Date_1 = ""
Set f = Nothing
Set colFiles = New Collection
Set FSO = Nothing
Set objFSO = Nothing
Set objRegExp = Nothing
RecursiveFileSearch FilePath, objRegExp, colFiles, objFSO
End Sub
Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _
ByRef matchedFiles As Collection, ByRef objFSO As Object)
Dim objFolder As Object
Dim objFile As Object
Dim objSubfolder As Object
Dim objSubFolders As Object
'Get the folder object associated with the target directory
Set objFolder = objFSO.GetFolder(targetFolder)
'Loop through the files current folder
For Each objFile In objFolder.Files
If objRegExp.test(objFile) Then
matchedFiles.Add (objFile)
End If
Next
'Loop through the each of the sub folders recursively
Set objSubFolders = objFolder.Subfolders
For Each objSubfolder In objSubFolders
RecursiveFileSearch objSubfolder, objRegExp, matchedFiles, objFSO
Next
'Garbage Collection
Set objFolder = Nothing
Set objFile = Nothing
Set objSubFolders = Nothing
Set objSubfolder = Nothing
End Sub
Function FileExists(ByVal FileToTest As String) As Boolean
FileExists = (Dir(FileToTest) <> "")
End Function
Function StripNumber(stdText As String)
Dim str As String, i As Integer
'strips the number from a longer text string
stdText = Trim(stdText)
For i = 1 To Len(stdText)
If Not IsNumeric(Mid(stdText, i, 1)) Then
str = str & Mid(stdText, i, 1)
End If
Next i
StripNumber = str ' * 1
End Function

Want to show how many PDF files in a folder

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim lngFileCount As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet
Dim folderpath
folderpath = InputBox("N:\Files", "Folder Path")
Set objFolder = objFSO.GetFolder(folderpath)
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"
For Each objFile In objFolder.Files
If UCase$(Right$(objFile.Name, 4)) = ".PDF" Then
ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = Replace$(UCase$(objFile.Name), ".PDF", "")
Z = Z + 1
MsgBox objFolder.Count.Z & ": The total number file in folder: "
End If
Next
If Z = 0 Then
MsgBox "No PDF Files found"
End If
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
Try this:
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim lngFileCount As Long
Dim Z as Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet
Dim folderpath As String
folderpath = InputBox("N:\Files", "Folder Path")
Set objFolder = objFSO.GetFolder(folderpath)
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"
For Each objFile In objFolder.Files
If UCase$(Right$(objFile.Name, 4)) = ".PDF" Then
ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = Replace$(UCase$(objFile.Name), ".PDF", "")
Z = Z + 1
End If
Next
If Z = 0 Then
MsgBox "No PDF Files found"
Else
MsgBox "The total number of files in folder: " & Z
End If
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
I moved the MsgBox outside the loop so you only see it once with the total.
Also the property objFolder.Count.Z doesn't exist, you just want the variable Z which stores the count of your PDF files.
Use the following function to get the number of files
Function numberOfFiles(ByVal dirName As String, ByVal mask As String) As Long
On Error GoTo Catch
Dim maskName As String
maskName = dirName & mask
With CreateObject("wscript.shell")
numberOfFiles = UBound(Split(.exec("cmd /c Dir """ & maskName & """ /b/a").stdout.readall, vbCrLf)) - 1
End With
Exit Function
Catch:
numberOfFiles = 0
End Function
Test it with
Sub testIt()
Debug.Print numberOfFiles("D:\user\examples\", "*.pdf")
End Sub
Your code changes to
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim lngFileCount As Long
Dim Z As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet
Dim folderpath As String
folderpath = InputBox("N:\Files", "Folder Path")
Set objFolder = objFSO.GetFolder(folderpath)
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"
Z = numberOfFiles(folderpath, "*.PDF")
If Z = 0 Then
MsgBox "No PDF Files found"
Else
MsgBox "The total number of files in folder: " & Z
End If
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
and simply include the numberOfFiles function just below it.

VBA in Excel to Download all PDFs from Webpage

I am needing to download all the PDFs from a webpage and save them into a folder. The PDFs on the webpage are downloaded via different links. Here is the webpage that the PDFs are located: NRCS Engineering Manuals and Handbooks | NRCS North Dakota. I have already created the folder location as shown below:
Function FileFolderExists(strFullPath As String) As Boolean
'Macro Purpose: Check if a folder exists
On Error GoTo EarlyExit
If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True
EarlyExit:
On Error GoTo 0
End Function
'Creates file folder for saving imported precipitation data
'Used as Micro for "Make Destination Folder" Button
Sub Make_Folder()
Dim objFSO As Object
Dim objFolder As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder(CurDir())
Range("u11").Select
Selection.ClearContents
' Opens windows explorer for creation of folder to save .pdf files
If Len(Dir(CurDir() & "\Stockwater PDFs", vbDirectory)) = 0 Then MkDir(CurDir() & "\Stockwater PDFs")
If FileFolderExists(CurDir() & "\Stockwater PDFs") Then
MsgBox "Folder Created Sucessfully!!!"
Else
MsgBox "Folder does not exist!"
End If
If FileFolderExists(CurDir() & "\Stockwater PDFs") Then
ActiveSheet.Range("u11").Value = "Stockwater PDFs folder made in the " & objFolder.Name
End If
End Sub
Once the files are downloaded from the website (the first part of the code below that I need help with) I would then list what files are located within the folder they were saved into (which I have already):
Sub GetWebPageDocs()
' Erases all listed files shown to be located in the CurDir()\Stockwater PDFs folder
Range("n17:n50").Select
Selection.ClearContents
Range("n16").Select
' Lists current files located in the CurDir()\Stockwater PDFs folder
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder(CurDir() & "\Stockwater PDFs")
irow = 17
icolumn = 14
ActiveSheet.Range("N16").Value = "The files found in the " & objFolder.Name & " folder are:"
'Loop through the Files collection
For Each objFile In objFolder.Files
ActiveSheet.Cells(irow, icolumn).Value = objFile.Name
irow = irow + 1
icolumn = icolumn
Next
'Clean up!
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
If it would be easier to have all the desired PDFs located within a ZIP file that was a single link on the website then that may be the best option.
Thanks in advance for the help.
I have tried the following but get a compile error on Dim xHTTP As MSXML2.XMLHTTP
Dim sUrl As String
Dim xHttp As MSXML2.XMLHTTP
Dim hDoc As MSHTML.HTMLDocument
Dim hAnchor As MSHTML.HTMLAnchorElement
Dim Ret As Long
Dim sPath As String
Dim i As Long
sPath = CurDir() & "\Stockwater PDFs"
sUrl = "http://www.nrcs.usda.gov/wps/portal/nrcs/detail/nd/technical/engineering/?cid=stelprdb1269591"
'Get the directory listing
Set xHttp = New MSXML2.XMLHTTP
xHttp.Open "GET", sUrl
xHttp.send
'Wait for the page to load
Do Until xHttp.readyState = 4
DoEvents
Loop
'Put the page in an HTML document
Set hDoc = New MSHTML.HTMLDocument
hDoc.body.innerHTML = xHttp.responseText
'Loop through the hyperlinks on the directory listing
For i = 0 To hDoc.getElementsByTagName("a").Length - 1
Set hAnchor = hDoc.getElementsByTagName("a").Item(i)
'test the pathname to see if it matches your pattern
If hAnchor.pathname Like "*.pdf" Then
Ret = URLDownloadToFile(0, sUrl & hAnchor.pathname, sPath & hAnchor.pathname, 0, 0)
If Ret = 0 Then
Debug.Print sUrl & hAnchor.pathname & " downloaded to " & sPath
Else
Debug.Print sUrl & hAnchor.pathname & " not downloaded"
End If
End If
Next i

How to move Workbooks from one folder to another with conditions?

There is a ready script that counts number of rows in Workbooks from a selected folder. In case number of rows in any workbook is more than 1, this workbook is copied and saved into another folder.
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
Dim TargetWB As Workbook
MyFolder = GetFolder("C:\Users\user\Desktop")
MyFile = Dir(MyFolder & "*.*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While MyFile <> ""
Set TargetWB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile & "*.*")
With TargetWB
If CountUsedRows(TargetWB) > 1 Then
.SaveAs "C:\Users\user\Desktop\vba\" & MyFile
End If
.Close
End With
MyFile = Dir
Loop
'Workbooks.Close savechanges:=False
Shell "explorer.exe C:\Users\user\Desktop\vba", vbMaximizedFocus
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Function CountUsedRows(Wbk As Workbook) As Long
Dim WS As Worksheet
Set WS = Wbk.Sheets(1)
CountUsedRows = WS.Range("A" & Rows.Count).End(xlUp).Row
End Function
Is it possible to move a Worbook to another folder insted of coping it in case it contains more than 1 row.
And is it possible to use something like: Workbooks.Close savechanges:=False in order to close chosen Workbooks after rows counting? Thanks!
You can move a file easily using the MoveFile method of FileSystemObject object. To use this type with early binding add a reference to Microsoft Sripting Runtime in your VBA project.

Searching excel files for specific sheets to create a list

I have worked on this for a while. It's my first Excel VBA macro and I think I am almost there. I just can't seem to find a way to get the information I need from my function or I can't get my function to give me the right information.
I need a macro that will search through a selected folder and its sub-folders for excel workbooks that have specific sheet names contained with in then out put the paths to an excel spreadsheet. Currently my code will either only find the files in a single folder or it will list all the files indiscriminately. Now the code is a bit of a mess because i am unsure of which parts I need and which parts I don't.
Option Explicit
Public ObjFolder As Object
Public objFso As Object
Public objFldLoop As Object
Public lngCounter As Long
Public objFl As Object
Sub ImportSheet()
Dim i As Integer
Dim SourceFolder As String
Dim FileList As Variant
Dim GrabSheet As String
Dim FileType As String
Dim ActWorkBk As String
Dim ImpWorkBk As String
Dim NoImport As Boolean
Dim FileToWriteTo As Variant
Dim xRow As Long
Dim xDirect$, xFname$, InitialFoldr$
Dim MyDir As String, myList()
'Startup folder to begin filedialog search
InitialFoldr$ = "C:"
'Define filetype
FileType = "*.xlsx"
'Define sheetname to copy
GrabSheet = Application.InputBox(prompt:="Please enter name of sheet you wish to find.", Title:="Specify Sheet Name")
'open dialog for user to select a folder to search
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
If .Show = True Then
MyDir = .SelectedItems(1)
End If
End With
On Error Resume Next
myList = SearchFiles(MyDir, "*.xlsx", 0, myList())
If Err = 0 Then
'If user selects folder count the items to search
xDirect$ = MyDir & "\"
xFname$ = Dir(xDirect$, 8)
'Creates list with filenames
FileList = ListFiles(xDirect$ & FileType)
'Imports data
Application.ScreenUpdating = False
ActWorkBk = ActiveWorkbook.Name
NoImport = False
'Clear contents of Active sheet and set active cell to A1
Sheets(1).UsedRange.ClearContents
Sheets(1).Select
Range("A1").Select
For i = 1 To UBound(FileList)
'Opens file
Workbooks.Open (xDirect$ & FileList(i))
ImpWorkBk = ActiveWorkbook.Name
'Checks to see if the specific sheet exists in the workbook
On Error Resume Next
ActiveWorkbook.Sheets(GrabSheet).Select
If Err > 0 Then
NoImport = True
GoTo nxt
End If
Err.Clear
On Error GoTo 0
xFname$ = Dir(xDirect$ & FileList(i))
Do While xFname$ <> ""
ThisWorkbook.Activate
ActiveCell.Offset(xRow) = xDirect$ & xFname$
xRow = xRow + 1
xFname$ = Dir
Loop
'Copies sheet
'ActiveWorkbook.Sheets(GrabSheet).Copy after:=Workbooks(ActWorkBk).Sheets(Workbooks(ActWorkBk).Sheets.Count)
'Renames the imported sheet
On Error Resume Next
ActiveSheet.Name = "Specs with " & GrabSheet
Err.Clear
On Error GoTo 0
nxt:
'Closes importfile
Workbooks(ImpWorkBk).Activate
Application.DisplayAlerts = False
ActiveWorkbook.Saved = True
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
'Workbooks(ActWorkBk).Activate
Next i
'Error if some sheets were not found
' If NoImport = True Then MsgBox "Some of the files did not contain the sheet " & GrabSheet
Application.ScreenUpdating = True
Else
MsgBox "No file found"
End If
On Error GoTo 0
' End If
'End With
'End Function
End Sub
'WITH SUBFOLDERS - Function that creates an array with all the files in the folder
Private Function SearchFiles(MyDir As String, myFileName As String, n As Long, myList()) As Variant
Dim fso As Object, myFolder As Object, myFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
For Each myFile In fso.getfolder(MyDir).Files
If (Not myFile.Name Like "~$*") * (myFile.Name <> ThisWorkbook.Name) _
* (myFile.Name Like myFileName) Then
n = n + 1
ReDim Preserve myList(1 To 2, 1 To n)
myList(1, n) = MyDir
myList(2, n) = myFile.Name
End If
Next
For Each myFolder In fso.getfolder(MyDir).subfolders
SearchFiles = SearchFiles(myFolder.Path, myFileName, n, myList)
Next
SearchFiles = IIf(n > 0, myList, "")
End Function
'WITHOUT SUBFOLDERS - Function that creates an array with all the files in the folder
Function ListFiles(Source As String) As Variant
Dim GetFileNames() As Variant
Dim i As Integer
Dim FileName As String
On Error GoTo ErrHndlr
i = 0
FileName = Dir(Source)
If FileName = "" Then GoTo ErrHndlr
'Loops until no more mathing files are found
Do While FileName <> ""
i = i + 1
ReDim Preserve GetFileNames(1 To i)
GetFileNames(i) = FileName
FileName = Dir()
Loop
ListFiles = GetFileNames
On Error GoTo 0
Exit Function
'If error
ErrHndlr:
ListFiles = False
On Error GoTo 0
End Function
This will work right now to give a list using the "ListFiles" Function.
But I can't seem to figure out how to get it to out put a list using the "SearchFiles" Function. Which, ultimately,is what I need it to do.
Please help i feel like I am so close!!!
Ok i figured it out. I was having trouble with the syntax to access my array of arrays. here is the code that ended up doing the trick.
Option Explicit
Public ObjFolder As Object
Public objFso As Object
Public objFldLoop As Object
Public lngCounter As Long
Public objFl As Object
Sub ImportSheet()
Dim i As Integer
Dim GrabSheet As String
Dim ActWorkBk As String
Dim ImpWorkBk As String
Dim NoImport As Boolean
Dim xRow As Long
Dim xFname As String
Dim InitialFoldr As String
Dim MyDir As String, myList()
'Startup folder to begin filedialog search
InitialFoldr = "C:\Users\george.EASYWAY\Desktop\TEST1\"
'Define sheetname to copy
GrabSheet = Application.InputBox(prompt:="Please enter name of sheet you wish to find.", Default:="snagit", Title:="Specify Sheet Name")
'open dialog for user to select a folder to search
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr
If .Show = True Then
MyDir = .SelectedItems(1)
End If
End With
On Error Resume Next
myList = SearchFiles(MyDir, "*.xlsx", 0, myList())
If Err = 0 Then
'Imports data
Application.ScreenUpdating = False
ActWorkBk = ActiveWorkbook.Name
NoImport = False
'Clear contents of Active sheet and set active cell to A1
Sheets(1).UsedRange.ClearContents
Sheets(1).Select
Range("A1").Select
For i = 1 To UBound(myList, 2)
'Opens file
Workbooks.Open (myList(1, (i)) & "\" & (myList(2, (i))))
ImpWorkBk = ActiveWorkbook.Name
'Checks to see if the specific sheet exists in the workbook
On Error Resume Next
ActiveWorkbook.Sheets(GrabSheet).Select
If Err > 0 Then
NoImport = True
GoTo nxt
End If
Err.Clear
On Error GoTo 0
xFname = Dir(myList(1, (i)) & "\" & (myList(2, (i))))
Do While xFname <> ""
ThisWorkbook.Activate
ActiveCell.Offset(xRow) = (myList(1, (i)) & "\" & (myList(2, (i))))
xRow = xRow + 1
xFname = Dir
Loop
'Renames the imported sheet
On Error Resume Next
ActiveSheet.Name = "Specs with " & GrabSheet
Err.Clear
On Error GoTo 0
nxt:
'Closes importfile
Workbooks(ImpWorkBk).Activate
Application.DisplayAlerts = False
ActiveWorkbook.Saved = True
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
'Workbooks(ActWorkBk).Activate
Next i
'Error if some sheets were not found
' If NoImport = True Then MsgBox "Some of the files did not contain the sheet " & GrabSheet
Application.ScreenUpdating = True
Else
MsgBox "No file found"
End If
On Error GoTo 0
End Sub
'Function that creates an array with all the files in the folder with subfolders
Function SearchFiles(MyDir As String, myFileName As String, n As Long, myList()) As Variant
Dim fso As Object, myFolder As Object, myFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
For Each myFile In fso.getfolder(MyDir).Files
If (Not myFile.Name Like "~$*") * (myFile.Name <> ThisWorkbook.Name) _
* (myFile.Name Like myFileName) Then
n = n + 1
ReDim Preserve myList(1 To 2, 1 To n)
myList(1, n) = MyDir
myList(2, n) = myFile.Name
End If
Next
For Each myFolder In fso.getfolder(MyDir).subfolders
SearchFiles = SearchFiles(myFolder.Path, myFileName, n, myList)
Next
SearchFiles = IIf(n > 0, myList, "")
End Function