vb6自学吧 关注:49贴子:339
  • 2回复贴,共1

vb6 文本文件的操作实例

只看楼主收藏回复

1:将txt文件内容全部添加到text1文本框:
Private Sub Form_Load() '加载txt文件
  Open App.Path & "\1.txt" For Input As #1
    Text1 = StrConv(InputB(LOF(1), 1), vbUnicode)
  Close #1
End Sub
2:从txt文件中逐行(段落)添加到文本框:
Private Sub Form_Load() '加载txt文件
  Open App.Path & "\1.txt" For Input As #1
End Sub
Private Sub Command1_Click() '开始阅读
Dim str As String
  On Error Resume Next
  Line Input #1, str
  Text1.SelText = str & vbCrLf
End Sub
Private Sub Command2_Click() '从头再看
  Close #1
  Text1 = ""
  Form_Load
End Sub


IP属地:湖南1楼2020-05-12 03:50回复
    3:替换1.txt指定行,并保存到1.txt:
    Private Sub Command1_Click()
    Dim s As String, n As Long
      Open App.Path & "\1.txt" For Input As #1 '指定要改的文件
      Open App.Path & "\1(备).txt" For Output As #2
        Do While Not EOF(1)
          Line Input #1, s
          n = n + 1
          If n = Val(Text1) Then s = Text2 'text1替换的行text2替换的内容
          Print #2, s
        Loop
      Close
      Kill App.Path & "\1.txt"'删除源文件
      Name App.Path & "\1(备).txt" As App.Path & "\1.txt"'备用文件修改为原文件名
    End Sub


    IP属地:湖南2楼2020-05-12 03:56
    回复
      4:偶数行添加新的行:
      例如原txt内容如下:
      AAAA
      BBBB
      CCCC
      DDDDD
      --------------------------------------------------------------------------
      修改为:
      b1
         AAAA
         BBBB
      end1
      b2
         CCCC
         DDDDD
      end2
      --------------------------------------------------------------------------
      Private Sub Command1_Click()
      Dim s$, b$, i&, n&
        Open App.Path & "\2.txt" For Input As #1 '要修改的文件
        Open App.Path & "\a.txt" For Output As #2 '存储到新的文件
        n = 1
          Do While Not EOF(1)
            Print #2, "b"; n '添加行
            Line Input #1, a
            Print #2, a
            Line Input #1, a
            Print #2, a
            Print #2, "end"; n '添加行
            n = n + 1
          Loop
        Close
      End Sub
      5:和上面一样模式,不会认为你是否是奇数行还是偶数行:
      例如原txt内容如下:
      AAAA
      BBBB
      CCCC
      DDDDD
      EEEE
      --------------------------------------------------------------------------
      修改为:
      b1
         AAAA
         BBBB
      end1
      b2
         CCCC
         DDDDD
      end2
      b3
         EEEE
      end3
      --------------------------------------------------------------------------
      Private Sub Command1_Click()
      Dim s$, b$, i&, n&
        Open App.Path & "\2.txt" For Input As #1 '要修改的文件
        Open App.Path & "\a.txt" For Output As #2 '存储到新的文件
          Do While Not EOF(1)
            Line Input #1, s
            i = i + 1
            If i Mod 2 Then
              n = n + 1
              b = "b" & n & vbCrLf & s
            Else
              b = s & vbCrLf & "end" & n
            End If
            Print #2, b
          Loop
            If n Mod 2 Then Print #2, "end" & n
        Close
      End Sub


      IP属地:湖南3楼2020-05-12 04:17
      回复