对VBA来说很新,我正在尝试编写一个小宏来编辑文本文件,以使它们在我们正在使用的不同程序中工作。我几乎把它整理好了,但有一件事让我烦恼。
我编写宏来筛选某些行的文本文件,并编辑/删除这些行中的文本并将其写入新文件。
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("tempRO.txt")
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If Not InStr(strLine, "COVXX ") = 0 Then
FileContentE = Left(FileContentE, InStr(FileContentE, "COVXX") - 1) & vbCrLf & strLine
End If
Loop
objFile.Close
我希望宏删除“COVXX”之后的所有文本。它编辑并将所有行写入FileContentE而没有问题,除了最后一行。不知怎的,它不会编辑最后一行。输出是这样的:
data,data,data
data,data,data
data,data,data
data,data,data, COVXX 123124123521346247
(eof)
有没有人知道我在这里做错了什么?提前感谢您的所有答案!
的奥斯卡
答案 0 :(得分:0)
像这样更新您的代码
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("tempRO.txt")
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
FileContentE = FileContentE & Left$(strLine, InStr(strLine, "COVXX") - 3) & vbCrLf
Loop
objFile.Close
但是处理内存中的整个文件会更快
Option Explicit
Public Sub TestCOVXX()
Debug.Print RemoveCOVXX("tempRO.txt")
End Sub
Public Function RemoveCOVXX(ByVal fName As String) As String
Const FIND_TEXT = "COVXX"
Dim fileNum As String, fileTxt As String, x As Variant, i As Long
fileNum = FreeFile
Open fName For Input As fileNum 'Open file
fileTxt = Input(LOF(fileNum), fileNum) 'Get file content in fileTxt
Close fileNum
x = Split(fileTxt, vbNewLine)
For i = 0 To UBound(x)
x(i) = Left$(x(i), InStr(x(i), FIND_TEXT) - 3)
Next
RemoveCOVXX = Join(x, vbCrLf)
End Function
我的测试文件:
data,data,data, COVXX 123124123521346247
data,data,data, COVXX 123124123521346247
data,data,data, COVXX 123124123521346247
data,data,data, COVXX 123124123521346247
结果
data,data,data
data,data,data
data,data,data
data,data,data