EXCEL macro : How to get all the file name from a folder, list the file name into a file then open the file to view it

This post will show you how to get  all the file name from a folder, list the file name into a file then open the file to view it. For this code example, I will try to get all the file name from my C:\Users\Public\Pictures\Sample Pictures folder. You can can this file name folder to whatever folder name that you want. Then I will output this result to ScriptOutput.txt on my desktop than open it.
The code is as below
=====================================================
 Sub getfilename()  
 Dim fso, folder, files, OutputFile  
 Dim strPath  
   Myuser = Environ("userprofile")  
   Myuserdesktop = Myuser & "\Desktop"  
 ' Create a FileSystemObject  
   Set fso = CreateObject("Scripting.FileSystemObject")  
 ' Define folder we want to list files from  
   strPath = "C:\Users\Public\Pictures\Sample Pictures"  
   Set folder = fso.GetFolder(strPath)  
   Set files = folder.files  
 ' Create text file to output test data  
   Set OutputFile = fso.CreateTextFile(Myuserdesktop & "\ScriptOutput.txt", True)  
 ' Loop through each file  
   For Each Item In files  
  ' Output file properties to a text file  
  OutputFile.WriteLine (Item.Name)  
   Next  
 ' Close text file  
   OutputFile.Close  
 ' View text file  
   Set objShell = CreateObject("Shell.Application")  
   objShell.ShellExecute Myuserdesktop & "\ScriptOutput.txt"  
 End Sub  
=====================================================

No comments:

Post a Comment