簡體   English   中英

使用vba宏從文件夾中的txt文件中刪除標題中的2行

[英]Delete 2 lines from header in txt files in a folder using vba macro

您好我使用下面的宏刪除文件夾中的前兩行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

在運行此腳本時,我遇到了類型不匹配錯誤的行For For fil in fld

如果有人可以協助解決這個問題,我將不勝感激

.GetFolder沒有做你想象的那樣。 它返回一個文件夾對象。 您想要文件夾中的文件。

試試吧,

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

TBH,我不知道你為什么不使用帶有* .txt文件掩碼的簡單Dir。

遍歷文件夾中的文件,使用DIR由Jeeped的建議。 您可能希望看到此stackoverflow鏈接

使用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

我還假設文本文件中有兩行以上。 如果沒有,那么你將不得不相應地處理。

正如Jeeped回答的那樣,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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM