使用vba宏从文件夹中txt文件的标题中删除2行
Hi im使用下面的宏删除文件夹中的前2行txt文件使用vba宏从文件夹中txt文件的标题中删除2行,vba,excel,Vba,Excel,Hi im使用下面的宏删除文件夹中的前2行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(f
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中的每个fil
如果有人能帮助解决此问题,我们将不胜感激。。GetFolder并没有做您认为应该做的事情。它返回一个文件夹对象。您需要文件夹中的文件 试试看
Set fld = FSO.GetFolder("O:\New folder\")
For Each fil In fld.Files
...
Next fil
TBH,我不知道您为什么不使用带有*.txt文件掩码的更简单的目录。正如Jeeped所回答的,使用目录可能更简单。 另外,用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
要循环浏览文件夹中的文件,请按照Jeeped的建议使用
DIR
。您可能需要查看此stackoverflow链接
使用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
我还假设文本文件中有两行以上。如果没有,那么你将不得不相应地处理