Private Sub Command1_Click()
writeline "c:\error.txt", 3, "123456"
End Sub
Sub writeline(txtpath As String, linenum As Integer, mystr As String) '修改指定行内容为MYSTR
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) Then MsgBox "行溢出", 64, "err!": Exit Sub
If linenum <= UBound(x) Then x(linenum - 1) = mystr
Open txtpath For Binary As 1
Put #1, , Join(x, vbCrLf)
Close 1
Set x = Nothing
End Sub
Function readline(txtpath As String, linenum As Integer) 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)
MsgBox "该文件一共 " & UBound(x) + 1 & " 行" '返回行数
If linenum > UBound(x) Then MsgBox "行溢出", 64, "err!": Exit Function
If linenum <= UBound(x) Then readline = x(linenum - 1)
Set x = Nothing
End Function
Sub writeline(txtpath As String, linenum As Integer, mystr As String) '修改指定行内容为MYSTR
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) Then MsgBox "行溢出", 64, "err!": Exit Sub
If linenum <= UBound(x) Then x(linenum - 1) = mystr
Open txtpath For Binary As 1
Print #1, , Join(x, vbCrLf)
Close 1
Set x = Nothing
End Sub
Private Sub Command1_Click()
MsgBox readline("C:\XXX.TXT", 120) '第120行内容
writeline "C:\XXX.TXT", 120, "123456" '修改该行内容为"123456"
End Sub