Sub replaceline(txtpath As String, ByVal linenum As Integer, ByVal mystr As String)
Dim filetxt As String, x As Variant, i As Integer
filetxt = String(FileLen(txtpath), " ")
Open txtpath For Binary As 1
Get #1, , filetxt
Close 1
x = Split(filetxt, vbCrLf)
If linenum <= UBound(x) + 1 Then
x(linenum - 1) = mystr
End If
Open txtpath For Binary As 1
Put #1, , Join(x, vbCrLf)
Close 1
Set x = Nothing
MsgBox "ok!"
End Sub
Private Sub Command1_Click()
replaceline "d:\xxxx.txt", 8, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
End Sub
解决的代码
Sub 提取奇数位数据(strSourceFile As String, strTargetFile As String)
Dim filenum As Integer
Dim fileContents As String
Dim fileInfo() As String
Dim i As Integer
Dim j As Integer
Dim tmpDemData As String
filenum = FreeFile
Open strSourceFile For Binary As #filenum
fileContents = Space(LOF(filenum))
Get #filenum, , fileContents
Close filenum
fileInfo = Split(fileContents, vbCrLf)
'取出源文件行数,按照回车换行来分隔成数组
filenum = FreeFile
tmpDemData = ""
If Dir(strTargetFile, vbNormal) <> "" Then
Kill strTargetFile
End If
Dim Filestr() As String
Open strTargetFile For Append As #filenum
'循环每一行
For i = 0 To UBound(fileInfo) - 1
Filestr = Split(Trim(fileInfo(i)), ",") '按照逗号分隔每一行的数据
tmpDemData = ""
For j = 0 To UBound(Filestr)
'判断是否为奇数位
If (j Mod 2) = 0 Then
tmpDemData = tmpDemData & Filestr(j)
ElseIf j <> 0 And j <> UBound(Filestr) Then
tmpDemData = tmpDemData & ","
End If
Next
'保存一行如目标文件
Print #filenum, tmpDemData
Next
Close #filenum
MsgBox "完毕"
End Sub
Private Sub Command1_Click()
提取奇数位数据 "d:\aa.txt", "d:\bb.txt"
End Sub
顺便说一下,northwolves(野性的呼唤) 的代码存在问题,问题是当文件中包含中文时,他的代码会在文件尾部产生多余的空格,这是由:
filetxt = String(FileLen(txtpath), " ")
所造成的,修正如下:
Sub replaceline(txtpath As String, ByVal linenum As Integer, ByVal mystr As String)
Dim filetxt As String, x As Variant, i As Integer
dim j as long
dim buff() as byte
j=filelen(txtpath)
redim buff(j-1)
Open txtpath For Binary As 1
Get #1, , buff
Close 1
filetxt=strconv(buff,vbunicode)
x = Split(filetxt, vbCrLf)
If linenum <= UBound(x) + 1 Then
x(linenum - 1) = mystr
End If
Open txtpath For Binary As 1
Put #1, , Join(x, vbCrLf)
Close 1
Set x = Nothing
MsgBox "ok!"
End Sub
Private Sub Command1_Click()
replaceline "d:\xxxx.txt", 8, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
End Sub