使用VBA宏从文件夹中txt文件的标题中删除2行

时间:2018-08-07 11:40:19

标签: excel vba excel-vba

您好,我使用下面的宏删除了文件夹中的前两行txt文件

Private Sub remove()

Dim FSO, txs, fld, fil As file, content, nLinesToSkip, i
Set FSO = CreateObject("Scripting.FileSystemObject")

nLinesToSkip = 2

fld = FSO.GetFolder("O:\New folder\")
For Each fil In fld
    If Right(fil.Name, 3) = "txt" Then

        Set txs = fil.OpenAsTextStream(1) ' 1 = for reading
        For i = 1 To nLinesToSkip
            txs.SkipLine
        Next i
        content = txs.ReadAll
        txs.Close

        Set txs = fil.OpenAsTextStream(2) ' 2 = for writing
        txs.Write content
        txs.Close

    End If
Next fil
End Sub

在运行此脚本时,我得到行的类型不匹配错误 对于fld中的每个文件

如果有人能协助解决此问题,我们将不胜感激

3 个答案:

答案 0 :(得分:1)

.GetFolder并没有按照您的想法去做。它返回一个文件夹对象。您希望文件位于文件夹中。

尝试一下,

Set fld = FSO.GetFolder("O:\New folder\")
For Each fil In fld.Files
    ...
Next fil

TBH,我不知道为什么您不使用带有* .txt文件掩码的简单Dir。

答案 1 :(得分:1)

要循环浏览文件夹中的文件,请使用Jeeped建议的DIR。您可能需要查看此stackoverflow链接

Loop through files in a folder using VBA

使用Excel编写/操作文本文件的过程较慢。这是一个更快的过程

Sub Sample()
    Dim MyData As String, strData() As String
    Dim MyFile As String

    MyFile = "C:\Users\routs\Desktop\Sample.Txt"

    '~~> Read the file in an array in 1 go
    Open MyFile For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    '~~> Delete old file
    Kill MyFile

    '~~> Write to new file
    Open MyFile For Output As #1

    '~~> From 3rd line onwards
    For i = 2 To UBound(strData)
        Print #1, strData(i)
    Next i

    Close #1
End Sub

如果您不想覆盖旧文件,请更改以下几行

    '~~> Delete old file
    Kill MyFile

    '~~> Write to new file
    Open MyFile For Output As #1

我还假设文本文件中多于2行。如果没有,那么您将不得不相应地进行处理。

答案 2 :(得分:0)

正如吉普回答的那样,使用Dir可能会更容易。 另外,用excel打开它会使操作对我来说稍微简单一些。

Sub Test()

    Dim StrFile As String
    Dim WB As Workbook
    Dim K As Integer
    Set WB = ActiveWorkbook

StrFile = Dir("O:\New folder\*.txt")

    Do While Len(StrFile) > 0

       Workbooks.Open Filename:="O:\New folder\" & StrFile
       Application.DisplayAlerts = False
           Rows("1:2").Delete Shift:=xlUp
           ActiveWorkbook.SaveAs Filename:="O:\New folder\" & StrFile, FileFormat:=xlText, CreateBackup:=False
           ActiveWindow.Close
       Application.DisplayAlerts = True

       StrFile = Dir

    Loop


End Sub