Store folder names into array and sort alphabetically VBA - excel

I have the following code which is meant to pull each file name in a specific path and place it into an array. For some reason, although the files in the File Explorer are sorted alphabetically, the code is pulling them out of order. My approach is to first store the file names into the array first, then sort the array afterwards. Is there a better way to approach this?
Additionally, for some reason the line with Debug.Print arr1(i) only prints blanks to the immediate window. Please advise.
Dim arr1(1000) As String, item As Variant
Dim x As Long, y As Long, k As Integer
Dim TempTxt1 As String
Dim TempTxt2 As String
Dim FolderPath As String, path As String, count As Integer
Dim size As Integer, i As Integer
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("X:\test\testfolder")
For Each oFile In oFolder.Files
arr1(i) = Left(oFile.Name, Application.WorksheetFunction.Find(".", oFile.Name) - 1)
i = i + 1
Debug.Print arr1(i)
Next oFile
'Alphabetize Sheet Names in Array List
For x = LBound(arr1) To UBound(arr1)
For y = x To UBound(arr1)
If UCase(arr1(y)) < UCase(arr1(x)) Then
TempTxt1 = arr1(x)
TempTxt2 = arr1(y)
arr1(x) = TempTxt2
arr1(y) = TempTxt1
End If
Next y
Next x
enter code here

So as per my comment; I think you might benefit from using ArrayList and its ability to Sort. Try:
Sub Test()
Dim oFSO As Object, oFolder As Object, arr As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("X:\test\testfolder")
Set arr = CreateObject("System.Collections.ArrayList")
For Each oFile In oFolder.Files
arr.Add oFSO.GetBaseName(oFile)
Next oFile
arr.Sort
End Sub
Since you pull in names one-by-one we might as well do so in the ArrayList. The .Sort method will then sort the list in ascending order.

Related

Setting a Path as a Variable in VBA

I am pretty new to the world of VBA, but I am having problem with a small part of a much larger code for an excel spreadsheet. My problem is that I am getting an "Invalid procedure call or argument" when trying to use a cell set as a variable and then plugging that variable into the path. It works when I set oFSO.GetFolder("Actual Path") as the actual path, but when I set a variable equal to a cell, which equals the path, it gives me this error. Thanks in advance!!
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Dim POSMVPath As Variant
Set POSMVPath = Range("C30").Value
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(POSMVPath)
Sheets.Add
ActiveSheet.Name = "DeleteSheet"
For Each oFile In oFolder.Files
Cells(i + 1, 1) = oFile.Name
i = i + 1
Next oFile```
Good afternoon.
Dim POSMVPath As Variant
when you define this variable you must define ti as a range instead of a Variant.

List files from a folder in a listbox with recent files showing first

I have a listbox that displays XLSM files from a folder Archive and PDFs from a folder called PDF in the folder of the main XLSM file, Main.
C:\Main\Archive\, C:\Main\PDF\, the XLSM looking up these items is located in the root folder C:\Main\
I would like to display the most recent modified files in descending order.
So if a file was created today, it would show on top followed by the one created yesterday and so on.
The code I have is just the standard AddItem to ListBox1
MyFile = Dir(MyFolder & "\*.xlsm")
Do While MyFile <> ""
ListBox1.AddItem MyFile
MyFile = Dir
Loop
These files also have names that start with either FSO or PPG followed by the "ticket number" like 1031, company name, job type and simple date.
FSO 10333 Co Name Job Type 042220.xlsm
PPG 10332 Co Name Job Type 042120.xlsm
That's how the names are displayed in the listbox. PDFs are the same name.
Thank you for your time!
What about the following:
Use of FileSystemObject to access file properties like: GetExtensionName, DateCreated and Name.
Use of Dictionary object to create a library and store values in memory.
Use of ArrayList object to create a list to store creation timedate values which we then can Sort ascending and Reverse to create an descending list.
We can then iterate ArrayList to return values from our Dictionary and add them to the ListBox in order.
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim arrList As Object: Set arrList = CreateObject("System.Collections.ArrayList")
Dim FSO: Set FSO = CreateObject("scripting.FileSystemObject")
Dim oFolder, oFile
Set oFolder = FSO.getfolder(MyFolder)
For Each oFile In oFolder.Files
If FSO.GetExtensionName(oFile) = "xlsm" Then
dict(oFile.DateCreated) = oFile.Name
arrList.Add oFile.DateCreated
End If
Next
arrList.Sort
arrList.Reverse
For i = 0 To arrList.Count - 1
ListBox1.AddItem dict(arrList(i))
Next
In support of my comment, omething like this will help you get the date from the file name. You can then use Excel to sort on this.
Sub testing()
Debug.Print get_date("FSO 10333 Co Name Job Type 042220.xlsm")
End Sub
Function get_date(strInput As String) As Date
Dim lngLength As Long
Dim lngLastSpace As Long
Dim strEndSection As String
lngLength = Len(strInput)
lngLastSpace = InStrRev(strInput, " ")
strEndSection = Mid(strInput, lngLastSpace)
strEndSection = Trim(Split(strEndSection, ".")(0)) ' The date bit
get_date = DateSerial(Mid(strEndSection, 5, 2), _
Mid(strEndSection, 1, 2), _
Mid(strEndSection, 3, 2))
End Function

Get a List of File Names with a Specific Extension

I want a list of file names with a specific extension.
I am using this guide: https://trumpexcel.com/list-of-file-names-from-a-folder-in-excel/
The code doesn't return any values.
I entered the formula and it seems to return the value, however, it results in an error. I removed the IfError to test if it is even working. See screenshot:
With the full formula used together with IfError, nothing gets called out, which is not supposed to happen:
Full formula returns nothing
Function GetFileNamesbyExt(ByVal FolderPath As String, FileExt As String) As Variant
Dim Result As Variant
Dim i As Integer
Dim MyFile As Object
Dim MyFSO As Object
Dim MyFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set MyFolder = MyFSO.GetFolder(FolderPath)
Set MyFiles = MyFolder.Files
ReDim Result(1 To MyFiles.Count)
i = 1
For Each MyFile In MyFiles
If InStr(1, MyFile.Name, FileExt) <> 0 Then
Result(i) = MyFile.Name
i = i + 1
End If
Next MyFile
ReDim Preserve Result(1 To i - 1)
GetFileNamesbyExt = Result
End Function
I managed to resolve the issue. Turns out that my Row() portion is wrong.
Because I am putting the formula in Row 47, my formula should have been:
=IFERROR(INDEX(GetFileNamesbyExt($CK$44,$CK$45),ROW()-46),"")
Many thanks all!

Search multiple text files for specific lines of data and import into excel using VBA macros

I am very new to VBA and I'm looking to use it to automate some of my processes. I have looked around this website (and others) and although I find very similar queries, I can't seem to find one that fits my needs exactly.
So far the closest thing I've found to what I'm looking to do is this: Wanting to create a search field and button to trigger VBA script to run
I have a source folder with all my data. My data is stored in multiple text files. Here is an example of what the data in the files looks like:
10001,1,205955.00
10001,2,196954.00
10001,3,4.60
10001,4,92353.00
10001,5,85015.00
10001,6,255.90
10001,7,804.79
10001,8,205955.00
10001,9,32465.00
In each row, the first number is a geographic code, second number is a numeric code for a specific indicator (not important for what I'm trying to do), and the third number is the value I want to import into my spreadsheet. Each geographic code is associated with 2247 rows.
I want to use a search box control in Excel that I can type a specific geographic code into, click a button and then the macro would run, searching the files for that specific code and then importing all the values - in the order they are listed in the data file - into my desired range in the workbook.
So far I've gotten this code written. Again, forgive me if this is bad code... I tried to re-purpose the code from the other forum post I mentioned earlier.
I think I setup the import location right... I want it to import into column C, row 3 of the sheet that the search box/button combo will be present on. But now, I am unsure how I would get the import aspect to work. Thanks in advance for anyone who can help on this issue.
Sub SearchFolders()
Dim FSO As Object
Dim Folder As Object
Dim File As Object
Dim TS As Object
Dim SourceFolder As String
Dim Search As String
Dim LineNumber As Long
Dim DataSh As Worksheet
SourceFolder = "C:\Users\MarMar\Desktop\Data\Census2016\DataFiles\"
Search = TextBox1.Value
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder(SourceFolder)
Set DataSh = ActiveSheet.Cells(3, 3)
For Each File In Folder.Files
Set TS = File.OpenAsTextStream()
LineNumber = 0
Do While Not TS.AtEndOfStream
LineNumber = LineNumber + 1
If InStr(TS.ReadLine, Search) Then
'Code to Import Values to DataSh ???
End If
Loop
TS.Close
Next File
End Sub
Maybe something like this:
Dim arr
For Each File In Folder.Files
Set TS = File.OpenAsTextStream()
LineNumber = 0
Do While Not TS.AtEndOfStream
arr = Split(TS.ReadLine, ",") 'split line to array
'check first element in array
If arr(0) = Search Then
datash.Resize(1, UBound(arr) + 1).Value = arr
Set datash = datash.Offset(1, 0)
End If
Loop
TS.Close
Next File
Final result that worked for me!
Sub SearchImportData1()
Dim FSO As Object
Dim SourceFolder As String
Dim Folder As Object
Dim Import As Range
Dim Search As String
Dim TextBox1 As TextBox
Dim File As Object
Dim TS As Object
Dim LineNumber As Integer
Dim Arr As Variant
SourceFolder = "C:\Users\MarMar\Desktop\Data\Census2016\DataFiles\"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder(SourceFolder)
Set Import = ActiveSheet.Cells(2, 3)
Search = ActiveSheet.TextBox1.Text
For Each File In Folder.Files
Set TS = File.OpenAsTextStream()
LineNumber = 0
Do While Not TS.AtEndOfStream
Arr = Split(TS.ReadLine, ",")
If Arr(0) = Search Then
Import.Resize(1, 1).Value = Arr(2)
Set Import = Import.Offset(1, 0)
End If
Loop
TS.Close
Next File
End Sub

looping a DateLastModified function through a column in excel

I have a worksheet with data but I need to add the time at which the Data was created. This time is the "Last Modified"-time of the file I got the data from.
I already got all the filenames as in "filename.txt" in the first column of the worksheet so each line of data can be referenced to its file. I have this function to pull the LastModified-Date from the filename:
Function FileLastModified(strFullFileName As String)
strFullFileName = "C:\...\filefolder\" + Range("A1").Value
Dim fs As Object, f As Object, s As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(strFullFileName)
s = UCase(strFullFileName) & vbCrLf
s = f.DateLastModified
FileLastModified = s
Set fs = Nothing: Set f = Nothing
End Function
Now I want the function to go through all the filenames in column A and put all the LastModified-Times in column D. So how do I edit this
strFullFileName = "C:\.....\" + Range("A1").Value
to automatically pull the filename from the A-Column?
Something like this?
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim i As Long
Dim n As Long
Dim filenames As Variant
Dim lastModifiedTimes As Variant
'How many filenames are there? (should tailor this to your exact situation)
n = Range("A:A").Find("*", Range("A1"), SearchDirection:=xlPrevious).Row
filenames = Range("A1").Resize(n, 1).Value 'load all fnames from sheet to array
ReDim lastModifiedTimes(1 To n, 1 To 1)
For i = 1 To n
lastModifiedTimes(i,1) = _
FSO.GetFile("C:\.....\" & filenames(i,1)).DateLastModified
Next i
'Slap times array onto sheet
Range("D1").Resize(n, 1).Value = lastModifiedTimes
Note that I got rid of your FileLastModified wrapper function since it's really only wrapping one thing, and it can be replaced by one single line of code.

Resources