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
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)
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.