0

My query is how to loop through all the files in a specific folder?

I’ve vba code snippet which deletes first and last line of “.b64” file. I want to achieve the same task with all the “.b64” files in a specific folder. Can someone help me tweak this code to loop it?

Here is a code...


Sub delline()

Dim objFSO As Object
Dim objStream As Object
Dim sLines
Dim iNumberOfLines
Dim i

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objStream = objFSO.OpenTextFile("C:\Testing\test1.b64", 1)
sLines = Split(objStream.ReadAll, vbCrLf)
objStream.Close

iNumberOfLines = UBound(sLines)

If iNumberOfLines > 2 Then
    Set objStream = objFSO.OpenTextFile("C:\Testing\test1.b64", 2)
    For i = 1 To iNumberOfLines - 2
        objStream.WriteLine sLines(i)
    Next
    objStream.Close
End If

Set objStream = Nothing
Set objFSO = Nothing


End Sub

Thanks! Jack

Community
  • 1
  • 1
JayeshG
  • 3
  • 1
  • 6
  • See the `Dir` function. – Paul Ogilvie Nov 01 '17 at 17:46
  • Google-fu: [that was hard](https://www.google.com/search?newwindow=1&safe=off&ei=4Af6WeHqMaekjwS15b-gDA&q=CreateObject%28"Scripting.FileSystemObject"%29++all+files&oq=CreateObject%28"Scripting.FileSystemObject"%29++all+files). – Excelosaurus Nov 01 '17 at 17:48
  • 1
    Possible duplicate of [Loop through files in a folder using VBA?](https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba) – MoondogsMaDawg Nov 01 '17 at 17:51

3 Answers3

0

You can use the Dir function. As an example:

ChDir "C:\MyDir"
nextfile = Dir("*.b64")
While (nextfile <> "")
    delline nextfile
    nextfile = Dir()
Wend

and declare delline as

Sub delline(filename)
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

Since you already are using the FileSystemObject...

Dim oFile as File
Dim oFolder as Folder
If objFSO.FolderExists(<Your Path>) Then
    Set oFolder = objFSO.GetFolder(<Your Path>)
    For Each oFile In oFolder.Files
        ... YOUR CODE

    Next
End If
Wayne G. Dunn
  • 4,282
  • 1
  • 12
  • 24
0

You can also use options in FSO which you have declared as below.

Sub dellineallfilesinafolder()

Dim objFSO As Object
Dim objStream As Object
Dim objFil As Object ' File Object
Dim sLines
Dim iNumberOfLines
Dim i

Set objFSO = CreateObject("Scripting.FileSystemObject")

For Each objFil In objFSO.GetFolder("C:\Testing").Files
    If LCase(objFSO.GetExtensionName(objFil.Path)) = "b64" Then
        Set objStream = objFSO.OpenTextFile(objFil.Path, 1)
        sLines = Split(objStream.ReadAll, vbCrLf)
        objStream.Close

        iNumberOfLines = UBound(sLines)

        If iNumberOfLines > 2 Then
            Set objStream = objFSO.OpenTextFile(objFil.Path, 2)
            For i = 1 To iNumberOfLines - 2
                objStream.WriteLine sLines(i)
            Next
            objStream.Close
        End If
    End If
Next objFil

Set objStream = Nothing
Set objFil = Nothing
Set objFSO = Nothing


End Sub
shrivallabha.redij
  • 5,832
  • 1
  • 12
  • 27