我需要帮助编辑记事本.csv文件中的文本。我有一个大文件,有太多的Excel行。我需要在记事本中打开该文件,在记事本中删除该文件的前15行,并将其另存为.txt文件。如果可能的话,我希望能够选择一个文件夹,其中包含我需要运行此宏的多个.csv的子文件夹。前15行并不总是包含相同的文本。有人可以帮我解决这个问题吗?
由于
答案 0 :(得分:4)
以下是从任何文本文件中删除前15行的过程示例(无论这些行的内容如何)。它应该能够处理任意大的文件,因为它一次只能在一行上运行。
Sub removeTopLines()
Dim srcFile As String, nSrc As Integer ' source file (read from)
Dim dstFile As String, nDst As Integer ' destination file (write to)
Dim textLine As String
Const LINES_TO_SKIP = 15
Dim lineCounter As Long
srcFile = "c:\opt\src.txt"
dstFile = "c:\opt\dst.txt"
nSrc = FreeFile
Open srcFile For Input As #nSrc
nDst = FreeFile
Open dstFile For Output As #nDst
lineCounter = 1
Do Until EOF(nSrc)
Line Input #nSrc, textLine
If lineCounter > LINES_TO_SKIP Then
Print #nDst, textLine
End If
lineCounter = lineCounter + 1
Loop
Close #nDst
Close #nSrc
End Sub
您可以看到how to traverse a directory tree here的示例,或者您可以只获取所有这些文件路径名的列表,并从另一个循环中调用此过程,一次为其提供一个文件。
更新:这是另一个版本,而不是行计数查找包含“时间”的字符串,并仅复制之后的行。
Sub removeTopLinesAfter()
Dim srcFile As String, nSrc As Integer ' source file (read from)
Dim dstFile As String, nDst As Integer ' destination file (write to)
Dim textLine As String, strAfter As String
strAfter = "time"
Dim copyLines As Boolean
srcFile = "c:\opt\src.txt"
dstFile = "c:\opt\dst.txt"
nSrc = FreeFile
Open srcFile For Input As #nSrc
nDst = FreeFile
Open dstFile For Output As #nDst
copyLines = False
Do Until EOF(nSrc)
Line Input #nSrc, textLine
If Not copyLines Then
copyLines = InStr(textLine, strAfter) > 0
Else
Print #nDst, textLine
End If
Loop
Close #nDst
Close #nSrc
End Sub