vb修改TXT指定行内容并在text中显示

有记事本1.txt内容如下
第一行
第二行
rvate onst set bbuttondownatc ccit=123456
rvate onst set bbuttondownatc ccit=456789
第五行
第六行

上面是代码.想在VB里面点击Command1的时候.第3行的内容123456显示在text1.text里面
第4行的内容456789显示在text2.text里面
并且修改了text1.text和text2.text里面的内容的话1.txt也会随之更改
重新运行程序的时候text1.text和text2.text还是能显示第3行第4行里面的内容

Dim FileBuffer As New Collection
Const Filename = "c:\1.txt" '文件名自己改一下
Dim Text_1 As String
Dim Text_2 As String
 
Private Sub Read() '读入文件
'可以在窗体load事件中或按钮事件中读入文件:
Dim FileNumber As Integer
FileNumber = FreeFile
Open Filename For Input As #FileNumber
Dim strLine As String
Do Until EOF(FileNumber)
    Line Input #FileNumber, strLine
    FileBuffer.Add strLine
Loop '把文件行读入到集合中
Text1 = Split(FileBuffer.Item(3), "=")(1)
Text2 = Split(FileBuffer.Item(4), "=")(1) '写入文本框
Text_1 = Text1
Text_2 = Text2
Close #FileNumber
End Sub
'-----------------------------------
Private Sub Save() '保存文件
    Dim a
    a = Split(FileBuffer.Item(3), "=")
    a(1) = Text1
    FileBuffer.Remove 3
    FileBuffer.Add Join(a, "="), , 3
    a = Split(FileBuffer.Item(4), "=")
    a(1) = Text2
    FileBuffer.Remove 4
    FileBuffer.Add Join(a, "="), , 4
    
    Dim FileNumber As Integer
    FileNumber = FreeFile
    Open Filename For Output As #FileNumber
    Dim i As Integer
    For i = 1 To FileBuffer.Count
        Print #FileNumber, FileBuffer.Item(i)
    Next
    Close #FileNumber
End Sub
'-----------------------------------------
Private Sub Form_Load() 
    Read '你也可以放在按钮事件中读取
End Sub
'--------------------------
Private Sub Form_Unload(Cancel As Integer)
    If Text1 <> Text_1 Or Text2 <> Text_2 Then Save
End Sub
'---------------------------
Private Sub Text1_Validate(Cancel As Boolean)
If Text1 <> Text_1 Then
Save
Text_1 = Text1
End If
End Sub
'----------------------------
Private Sub Text2_Validate(Cancel As Boolean)
If Text2 <> Text_2 Then
Save
Text_2 = Text2
End If
End Sub

'如果仅仅是在关闭窗口时更新文件,把文本框CausesValidation设置为false,否则设为true

追问

终于可以了.谢谢

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-06
Dim Ar
Dim FilePath    As String
Private Sub Form_Load()
    FilePath = "D:\1.TXT" '文本路径
    Open FilePath For Binary As #1
        Ar = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)
    Close #1
    Text1.Text = Split(Ar(2), "=")(1)
    Text2.Text = Split(Ar(3), "=")(1)
End Sub

Private Sub Text1_Change()
    Ar(2) = Left(Ar(2), InStr(Ar(2), "=")) & Text1.Text
    Save
End Sub
Private Sub Text2_Change()
    Ar(3) = Left(Ar(3), InStr(Ar(3), "=")) & Text2.Text
    Save
End Sub

Sub Save()
    Open FilePath For Output As #1
        Print #1, Join(Ar, vbCrLf)
    Close #1
End Sub

第2个回答  2013-08-06
vb6还是vb.net?