Search code examples
vbaloopsdirectoryvb6

How to get list of all subfolders in one folder and write it to txt file using vb


I want to know, how it possible to get list of all subfolders in "C/Windows" and write it to txt file. Here is my code:

Sub Check
MkDir "c:\New_Folder"

Dim iFileNo as Integer
Dim strFile As String
  strFile = "c:\New_Folder\data.txt" 'the file you want to save to
  intFile = FreeFile
  Open strFile For Output As #intFile
    Print #intFile, 
  Close #intFile

End Sub

Full Explanation: Write a program, like opening a folder on the D drive (the folder is your nickname). In this folder open the file data.txt, in which write down the names of all folders from the directory C: \ Windows. 2. Write a program that reads information from a file, which was opened with a first program and transfer through MsgBox skin another row to the file


Solution

  • Whenever a problem is defined as "get list of all subfolders" and "write to a text file", I know I likely need to implement a loop of some kind. As it turns out that is all that is missing from your code. The Dir command can help solve this problem:

    Private Sub Check()
       Dim intFile As Integer
       Dim strFile As String
       Dim FolderName As String
       
       MkDir "c:\New_Folder"
       strFile = "c:\New_Folder\data.txt"
       intFile = FreeFile
       Open strFile For Output As #intFile
       FolderName = Dir("c:\windows\", vbDirectory)
       
       Do While FolderName <> ""
          If FolderName <> "." And FolderName <> ".." And (GetAttr("c:\windows\" & FolderName) And vbDirectory) = vbDirectory Then
             Print #intFile, FolderName
          End If
    
          FolderName = Dir()
       Loop
       
       Close #intFile
    End Sub
    

    I would also encourage you to use proper formatting of your code, in this case indentation. It will make your life easier at some point!