如何遍历目录中的所有文件

时间:2017-11-01 17:42:13

标签: vba excel-vba excel

我的查询是如何遍历特定文件夹中的所有文件?

我有vba代码段,删除了“.b64”文件的第一行和最后一行。我希望与特定文件夹中的所有“.b64”文件实现相同的任务。有人可以帮我调整这段代码来循环吗?

这是一个代码......

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

谢谢! 千斤顶

3 个答案:

答案 0 :(得分:0)

您可以使用<select name="select1" [(ngModel)]="currentValue"> 功能。举个例子:

Dir

并将ChDir "C:\MyDir" nextfile = Dir("*.b64") While (nextfile <> "") delline nextfile nextfile = Dir() Wend 声明为

delline

答案 1 :(得分:0)

由于您已经在使用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

答案 2 :(得分:0)

您还可以使用FSO中的声明,如下所示。

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