How to loop through files in a folder Excel Mac 2016 - excel

I'm trying to combine several excel files into one. For this I've been using and modifying an old answer I found here, but I ran into trouble while running it on Excel 2016 for Mac (it worked ok with Excel 2011 for Mac, with some changes).
In Excel 2016 (Mac), the following code runs through the loop once, after which it prints the name of the first file in the selected folder, but then it stops.
In Excel 2011 (Mac), it correctly prints the names of all files in the selected folder.
Sub wat()
Dim FilesFolder As String, strFile As String
'mac excel 2011
'FilesFolder = MacScript("(choose folder with prompt ""dis"") as string")
'mac excel 2016
FilesFolder = MacScript("return posix path of (choose folder with prompt ""dat"") as string")
If FilesFolder = "" Then Exit Sub
strFile = Dir(FilesFolder)
Do While Len(strFile) > 0
Debug.Print "1. " & strFile
strFile = Dir
Loop
MsgBox "ded"
End Sub
So, I'm pretty new at this, but it looks to me like strFile = Dir is not working properly.
I looked at the Ron deBruin page:
Loop through Files in Folder on a Mac (Dir for Mac Excel)
but to be honest that was a little too complicated for me to comprehend and modify to my needs.
Any help is appreciated, and thanks for the patience!

Option Explicit
Sub GetFileNames()
'Modified from http://www.rondebruin.nl/mac/mac013.htm
Dim folderPath As String
Dim FileNameFilter As String
Dim ScriptToRun As String
Dim MyFiles As String
Dim Extensions As String
Dim Level As String
Dim MySplit As Variant
Dim FileInMyFiles As Long
Dim Fstr As String
Dim LastSep As String
'mac excel 2016
'Get the directory
On Error Resume Next 'MJN
folderPath = MacScript("choose folder as string") 'MJN
If folderPath = "" Then Exit Sub 'MJN
On Error GoTo 0 'MJN
'Set up default parameters to get one level of Folders
'All files
Level = "1"
Extensions = ".*"
'Set up filter for all file types
FileNameFilter = "'.*/[^~][^/]*\\." & Extensions & "$' " 'No Filter
'Set up the folder path to allow to work in script
folderPath = MacScript("tell text 1 thru -2 of " & Chr(34) & folderPath & _
Chr(34) & " to return quoted form of it's POSIX Path")
folderPath = Replace(folderPath, "'\''", "'\\''")
'Run the script
ScriptToRun = ScriptToRun & "do shell script """ & "find -E " & _
folderPath & " -iregex " & FileNameFilter & "-maxdepth " & _
Level & """ "
'Set the String MyFiles to the result of the script for processing
On Error Resume Next
MyFiles = MacScript(ScriptToRun)
On Error GoTo 0
'Clear the fist four columns of the current 1st sheet on the workbook
Sheets(1).Columns("A:D").Cells.Clear
'Split MyFiles and loop through all the files
MySplit = Split(MyFiles, Chr(13))
For FileInMyFiles = LBound(MySplit) To UBound(MySplit)
On Error Resume Next
Fstr = MySplit(FileInMyFiles)
LastSep = InStrRev(Fstr, Application.PathSeparator, , 1)
Sheets(1).Cells(FileInMyFiles + 1, 1).Value = Left(Fstr, LastSep - 1) 'Column A - Directory
Sheets(1).Cells(FileInMyFiles + 1, 2).Value = Mid(Fstr, LastSep + 1, Len(Fstr) - LastSep) 'Column B - file name
Sheets(1).Cells(FileInMyFiles + 1, 3).Value = FileDateTime(MySplit(FileInMyFiles)) 'Column C - Date
Sheets(1).Cells(FileInMyFiles + 1, 4).Value = FileLen(MySplit(FileInMyFiles)) 'Column D - size
On Error GoTo 0
Next FileInMyFiles
'Fit the contents
Sheets(1).Columns("A:D").AutoFit
End Sub

Related

Macro code erroring out in Mac OS for dialog box [duplicate]

Hi I am trying to list all the files in a subdirectory of where the Excel workbook is residing in. For some reason, the code cannot execute beyond the Dir function. Can anyone please advise? Thank you!
Sub ListFiles()
ActiveSheet.Name = "temp"
Dim MyDir As String
'Declare the variables
Dim strPath As String
Dim strFile As String
Dim r As Long
MyDir = ActiveWorkbook.Path 'current path where workbook is
strPath = MyDir & ":Current:" 'files within "Current" folder subdir, I am using Mac Excel 2011
'Insert the headers in Columns A, B, and C
Cells(1, "A").Value = "FileName"
Cells(1, "B").Value = "Size"
Cells(1, "C").Value = "Date/Time"
'Find the next available row
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
'Get the first file from the folder
'Note: macro stops working here
strFile = Dir(strPath & "*.csv", vbNormal)
'Loop through each file in the folder
Do While Len(strFile) > 0
'List the name, size, and date/time of the current file
Cells(r, 1).Value = strFile
Cells(r, 2).Value = FileLen(strPath & strFile)
Cells(r, 3).Value = FileDateTime(strPath & strFile)
'Determine the next row
r = r + 1
'Get the next file from the folder
strFile = Dir
Loop
'Change the width of the columns to achieve the best fit
Columns.AutoFit
End Sub
Gianna, you cannot use DIR like that in VBA-EXCEL 2011. I mean the wildcards are not supported. You have to use MACID for this purpose.
See this code sample (TRIED AND TESTED)
Sub Sample()
MyDir = ActiveWorkbook.Path
strPath = MyDir & ":"
strFile = Dir(strPath, MacID("TEXT"))
'Loop through each file in the folder
Do While Len(strFile) > 0
If Right(strFile, 3) = "csv" Then
Debug.Print strFile
End If
strFile = Dir
Loop
End Sub
See this link for more details on MACID
Topic: MacID Function
Link: http://office.microsoft.com/en-us/access-help/macid-function-HA001228879.aspx
EDIT:
In case that link ever dies which I doubt, here is an extract.
MacID Function
Used on the Macintosh to convert a 4-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.
Syntax
MacID(constant)
The required constant argument consists of 4 characters used to specify a resource type, file type, application signature, or Apple Event, for example, TEXT, OBIN, "XLS5" for Excel files ("XLS8" for Excel 97), Microsoft Word uses "W6BN" ("W8BN" for Word 97), and so on.
Remarks
MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support * and ? as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns TEXT type files from the current folder:
Dir("SomePath", MacID("TEXT"))
MacID is used with Shell and AppActivate to specify an application using the application's unique signature.
HTH
If Dir(outputFileName) <> "" Then
Dim ans
ans = MsgBox("File already exists.Do you wish to continue(the previous file will be deleted)?", vbYesNo)
If ans = vbNo Then
Exit Sub
Else
Kill outputFileName
End If
End If
For listitem = 0 To List6.ListCount() - 1
For the answer above, it worked for me when I took out the "TEXT" in MacID:
Sub LoopThruFiles()
Dim mydir As String
Dim foldercount As Integer
Dim Subjectnum As String
Dim strpath As String
Dim strfile As String
ChDir "HD:Main Folder:"
mydir = "HD:Main Folder:"
SecondaryFolder = "Folder 01:"
strpath = mydir & SecondaryFolder
strfile = Dir(strpath)
'Loop through each file in the folder
Do While Len(strfile) > 0
If Right(strfile, 3) = "cef" Then
MsgBox (strfile)
End If
strfile = Dir
Loop
End Sub

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.

Searching a folder for files matching different strings in an Excel range

I am using VBA to search a network folder with typically about 4000 .txt files and move the bad ones that contain strings listed in an excel range, to another folder. Remaining good files are zipped and moved/scattered and the .txt's moved to a single folder.
Here is my code that takes many hours to run, probably due to the double looping. Please help me with changing this to run faster/more efficient.
Option Compare Text
Sub SDRFiles()
Dim lastRow As Integer
Dim Fldr As Object
Dim BaseFldr As String
Dim sdrDNU As String
Dim sdrDateFldr As String
Dim fDate
Dim FSO As Object
Dim FirstTwo As String
Dim NineTen As String
Dim Lead As String
Dim BadFile As Integer
Dim sdrFile As String
Dim fldExists As String
'Process SDR files. Move files off landing zone to working folder, pull out and store bad files,
'zip good files and move to each owner's folder, save good txt in Data Czar's folder.
'Landing zone
BaseFldr = "\\nasgw013pn\hedis_prod\SDR FILES"
'new SDR folder for files
fDate = Format(Date, "mmddyyyy")
'Processing fldr
sdrDateFldr = BaseFldr & "\" & fDate & "_" & shControl.cboMonth.Value & theCycle
fldExists = Dir(sdrDateFldr)
If fldExists = "" Then
MkDir sdrDateFldr
End If
'Move all files from landing zone to processing folder
Set FSO = CreateObject("scripting.filesystemobject")
extn = "\*.txt"
FSO.MoveFile Source:=BaseFldr & extn, Destination:=sdrDateFldr & "\"
'Do Not Use sub folder for bad files
sdrDNU = sdrDateFldr & "\DNU"
fldExists = Dir(sdrDNU)
If fldExists = "" Then
MkDir sdrDNU
End If
'Good Text File destination
TextFileFldr = fDate & "_" & shControl.cboMonth.Value & theCycle & "_txt"
TextFileDest = sdrDateFldr & "\" & TextFileFldr
fldExists = Dir(TextFileDest)
If fldExists = "" Then
MkDir TextFileDest
End If
'Bottom of bad file strings
lastRow = shSDR.Range("A" & Rows.Count).End(xlUp).Row
Set xFolder = FSO.GetFolder(sdrDateFldr)
'loop thru folder
For Each xFile In xFolder.Files 'About 4000 files. can vary
Fname = xFile.Name
FirstTwo = Left(Fname, 2)
NineTen = Mid(Fname, 9, 2)
Lead = Mid(Fname, 16, 2)
'range with list of bad strings
For Each Item In shSDR.Range("A2:A" & lastRow) 'about 10 strings. can vary
'Hold file from 1st loop and test. If bad file, move to Do Not Use (DNU) folder
If InStr(Fname, Item) > 0 Or _
(InStr(Fname, "PWOEY") > 0 And FirstTwo <> "OH") Or _
(InStr(Fname, "HNARST") > 0 And FirstTwo <> NineTen) Or _
(InStr(Fname, "FTANDHEIPANE") > 0 And FirstTwo <> Lead) Then
'bad file - move to DNU Folder
Name sdrDateFldr & "\" & Fname As sdrDNU & "\" & Fname
'Bad file indentified
BadFile = 1
'exit this loop if matched and get next file
Exit For
End If
Next Item
If BadFile = 0 Then
'Good file - zip it and move each txt file to same folder
Call Zipp(sdrDateFldr & "\" & Replace(Fname, "txt", "zip"), sdrDateFldr & "\" & Fname)
‘move good zipped file to its own specific folder – NY folder, FL folder TX folder etc.
Call MoveIt(sdrDateFldr & "\" & Replace(Fname, "txt", "zip"), Replace(Fname, "txt", "zip"))
End If
BadFile = 0
Next xFile
End Sub
'says function but it really a sub
Public Function Zipp(ZipName, FileToZip)
'Called by all modules to create a Zip File
‘Dim FSO As Object
Dim oApp As Object
If Len(Dir(ZipName)) > 0 Then Kill (ZipName)
If Dir(ZipName) = "" Then
Open ZipName For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End If
dFile = Dir(FileToZip)
On Error Resume Next
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(CVar(ZipName)).CopyHere CVar(FileToZip)
DoEvents
'====HELP!!! ================Please help me with the following. It hangs sporadically, sometimes at
'============================file 200 or may the 1500th file. I have to esc esc and continue.
'============================For 10 to 20 files it seems to run fine
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(CVar(ZipName)).Items.Count = 1
Application.Wait (Now + TimeValue("0:00:06"))
DoEvents
Loop
'=============================================================================
'=============================================================================
'USED ONLY BY Sub SDRFiles()
'THIS PART OF ZIPP SAVES THE .TXT FILE TO DATA CZAR'S FOLDER
'SDR Processing - Move text file
If SDR = "Y" And Len(Dir(FileToZip)) > 0 Then
SetAttr FileToZip, vbNormal
Name FileToZip As TextFileDest & "\" & dFile
End If
Set oApp = Nothing
‘Set FSO = Nothing
End Function
Sub MoveIt(PathZip, ZipFileName)
Dim rootPlusSubFolder As String
Dim NasState As Range
Dim NasLocation As String
Dim FSO As Object
'MOVE ZIPP FILES TO FOLDERS
'MOVE FILES TO IMP FOLDER - find state in extract name and MOVE file to that folder
'Bottom of state list
botRow = shNasMoves.Cells(shNasMoves.Rows.Count, 7).End(xlUp).Row
'Bottom of list of import folder names
NasBot = Sheets("NASMoves").Cells(Rows.Count, "A").End(xlUp).Address
'Look up state to get import folder path
Application.FindFormat.Clear
Set NasState = shNasMoves.Range("A1:" & NasBot).Find(What:=Left(ZipFileName, 2))
'if state found, get folder location URL
If Not NasState Is Nothing Then
NasLocation = NasState.Offset(0, 1).Value
'current month for sub folder file name
CurMonthFolder = "CS_" & theMo & "_" & theCycle & "\"
'Combined destination folder and sub folder name
rootPlusSubFolder = NasLocation & CurMonthFolder
Set FSO = CreateObject("scripting.filesystemobject")
'if CS Import SUB folder doesn't exist, create it - sometimes DIR sometimes FSO
If Not FSO.FolderExists(rootPlusSubFolder) Then
FSO.CreateFolder (rootPlusSubFolder)
End If
'Final dest Fldr
If Not FSO.FolderExists(rootPlusSubFolder & "\" & "SDR") Then
FSO.CreateFolder (rootPlusSubFolder & "\" & "SDR")
End If
'try to stop pop up
With Application
.EnableEvents = False
.DisplayAlerts = False
End With
'Debug.Print rootPlusSubFolder & "SDR"
On Error Resume Next
'move file from Root to destination folder/sub folder
FSO.MoveFile PathZip, rootPlusSubFolder & "SDR\" & ZipFileName
With Application
.EnableEvents = True
.DisplayAlerts = True
End With
End If
End Sub

Search for a string and move files containing string from source folder to destination folder

I have large number of .csv files in a folder and each file has few separation codes in them. Separation code usually will be 5 digit code eg: B82A6.
I have to copy files with a certain separation code and move them to a destination folder.
I am new to VBA. I've been searching for code to modify it to my use.
Sub Test()
Dim R As Range, r1 As Range
Dim SourcePath As String, DestPath As String, SeperationCode As String
SourcePath = "C:\Users\hr315e\Downloads\Nov_03_2019\"
DestPath = "C:\Users\hr315e\Downloads\Target\"
Set r1 = Range("A1", Range("A" & Rows.Count).End(xlUp))
For Each R In r1
SeperationCode = Dir(SourcePath & R)
Do While SeperationCode <> ""
If Application.CountIf(r1, SeperationCode) Then
FileCopy SourcePath & SeperationCode, DestPath & SeperationCode
R.Offset(0, 1).Value = SeperationCode
Else
MsgBox "Bad file: " & SeperationCode & " ==>" & SeperationCode & "<== "
End If
SeperationCode = Dir(SourcePath & "B82A6" & R.Value & "B82A6")
Loop
Next
End Sub
So, here's the code that should work for you.
As you can see, this is a version of code which I linked to you with small updates:
Sub GoThroughFilesAndCopy()
Dim BrowseFolder As String, DestinationFolder As String
Dim FileItem As Object
Dim oFolder As Object
Dim FSO As Object
Dim TempFileName As String
Dim CheckCode As String
Application.ScreenUpdating = False
' selecting the folder with files
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select the folder with files"
.Show
On Error Resume Next
Err.Clear
BrowseFolder = .SelectedItems(1)
If Err.Number <> 0 Then
MsgBox "You didn't select anything!"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
End With
' or you may hardcode it (data from your post):
'BrowseFolder = "C:\Users\hr315e\Downloads\Nov_03_2019\"
' selecting the destination folder
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select the the destination folder"
.Show
On Error Resume Next
Err.Clear
DestinationFolder = .SelectedItems(1)
If Err.Number <> 0 Then
MsgBox "You didn't select anything!"
Application.ScreenUpdating = True
Exit Sub
End If
On Error GoTo 0
End With
' or you may hardcode it (data from your post):
'DestinationFolder = "C:\Users\hr315e\Downloads\Target\"
CheckCode = "Some string" ' this is you check code
Set FSO = CreateObject("Scripting.FileSystemObject") ' creating filesystem object
Set oFolder = FSO.getfolder(BrowseFolder) ' creating folder object
For Each FileItem In oFolder.Files 'looking through each file in selected forlder
TempFileName = ""
If UCase(FileItem.Name) Like "*.CSV*" Then 'try opening only .csv files
TempFileName = BrowseFolder & Application.PathSeparator & FileItem.Name ' getting the full name of the file (with full path)
If CheckTheFile(TempFileName, CheckCode) Then ' if the file passes the checking function
If Dir(DestinationFolder & Application.PathSeparator & FileItem.Name) = "" Then 'if the file doesn't exist in destination folder
FileCopy Source:=TempFileName, Destination:=DestinationFolder & Application.PathSeparator & FileItem.Name ' it is copied to destination
Else ' otherwise, there are to options how to deal with it further
'uncomment the part you need below:
' this will Overwrite existing file
'FSO.CopyFile Source:=TempFileName, Destination:=DestinationFolder & Application.PathSeparator & FileItem.Name
' this will get new name for file and save it as copy
'FileCopy Source:=TempFileName, Destination:=GetNewDestinationName(FileItem.Name, DestinationFolder)
End If
End If
End If
Next
Application.ScreenUpdating = True
End Sub
'////////////////////////////////////////////////////////////////////////
Function CheckTheFile(File As String, Check As String) As Boolean
Dim TestLine As String
Dim TestCondition As String
TestCondition = "*" & Check & "*" ' this is needed to look for specific text in the file, refer to Like operator fro details
CheckTheFile = False
Open File For Input As #1 ' open file to read it line by line
Do While Not EOF(1)
Line Input #1, TestLine ' put each line of the text to variable to be able to check it
If TestLine Like TestCondition Then ' if the line meets the condition
CheckTheFile = True ' then function gets True value, no need to check other lines as main condition is met
Close #1 ' don't forget to close the file, beacuse it will be still opened in background
Exit Function ' exit the loop and function
End If
Loop
Close #1 ' if condiotion is not found in file just close the file, beacuse it will be still opened in background
End Function
'////////////////////////////////////////////////////////////////////////
Function GetNewDestinationName(File As String, Destination As String) As String
Dim i As Integer: i = 1
Do Until Dir(Destination & Application.PathSeparator & "Copy (" & i & ") " & File) = "" ' if Dir(FilePath) returns "" (empty string) it means that the file does not exists, so can save new file with this name
i = i + 1 ' incrementing counter untill get a unique name
Loop
GetNewDestinationName = Destination & Application.PathSeparator & "Copy (" & i & ") " & File ' return new file name
End Function
Basically, there is one sub, which is mostly copy-paste from linked topic, and two simple functions.

Dir() function not working in Mac Excel 2011 VBA

Hi I am trying to list all the files in a subdirectory of where the Excel workbook is residing in. For some reason, the code cannot execute beyond the Dir function. Can anyone please advise? Thank you!
Sub ListFiles()
ActiveSheet.Name = "temp"
Dim MyDir As String
'Declare the variables
Dim strPath As String
Dim strFile As String
Dim r As Long
MyDir = ActiveWorkbook.Path 'current path where workbook is
strPath = MyDir & ":Current:" 'files within "Current" folder subdir, I am using Mac Excel 2011
'Insert the headers in Columns A, B, and C
Cells(1, "A").Value = "FileName"
Cells(1, "B").Value = "Size"
Cells(1, "C").Value = "Date/Time"
'Find the next available row
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
'Get the first file from the folder
'Note: macro stops working here
strFile = Dir(strPath & "*.csv", vbNormal)
'Loop through each file in the folder
Do While Len(strFile) > 0
'List the name, size, and date/time of the current file
Cells(r, 1).Value = strFile
Cells(r, 2).Value = FileLen(strPath & strFile)
Cells(r, 3).Value = FileDateTime(strPath & strFile)
'Determine the next row
r = r + 1
'Get the next file from the folder
strFile = Dir
Loop
'Change the width of the columns to achieve the best fit
Columns.AutoFit
End Sub
Gianna, you cannot use DIR like that in VBA-EXCEL 2011. I mean the wildcards are not supported. You have to use MACID for this purpose.
See this code sample (TRIED AND TESTED)
Sub Sample()
MyDir = ActiveWorkbook.Path
strPath = MyDir & ":"
strFile = Dir(strPath, MacID("TEXT"))
'Loop through each file in the folder
Do While Len(strFile) > 0
If Right(strFile, 3) = "csv" Then
Debug.Print strFile
End If
strFile = Dir
Loop
End Sub
See this link for more details on MACID
Topic: MacID Function
Link: http://office.microsoft.com/en-us/access-help/macid-function-HA001228879.aspx
EDIT:
In case that link ever dies which I doubt, here is an extract.
MacID Function
Used on the Macintosh to convert a 4-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.
Syntax
MacID(constant)
The required constant argument consists of 4 characters used to specify a resource type, file type, application signature, or Apple Event, for example, TEXT, OBIN, "XLS5" for Excel files ("XLS8" for Excel 97), Microsoft Word uses "W6BN" ("W8BN" for Word 97), and so on.
Remarks
MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support * and ? as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns TEXT type files from the current folder:
Dir("SomePath", MacID("TEXT"))
MacID is used with Shell and AppActivate to specify an application using the application's unique signature.
HTH
If Dir(outputFileName) <> "" Then
Dim ans
ans = MsgBox("File already exists.Do you wish to continue(the previous file will be deleted)?", vbYesNo)
If ans = vbNo Then
Exit Sub
Else
Kill outputFileName
End If
End If
For listitem = 0 To List6.ListCount() - 1
For the answer above, it worked for me when I took out the "TEXT" in MacID:
Sub LoopThruFiles()
Dim mydir As String
Dim foldercount As Integer
Dim Subjectnum As String
Dim strpath As String
Dim strfile As String
ChDir "HD:Main Folder:"
mydir = "HD:Main Folder:"
SecondaryFolder = "Folder 01:"
strpath = mydir & SecondaryFolder
strfile = Dir(strpath)
'Loop through each file in the folder
Do While Len(strfile) > 0
If Right(strfile, 3) = "cef" Then
MsgBox (strfile)
End If
strfile = Dir
Loop
End Sub

Resources