我需要用vb打开某个文本文件,定位到某一行,某一个位置,添加一个字符,然后保存,请问这样的代码如何实现

解决方案 »

  1.   

    文件整个读入字符串str1,用split(str1,vbCrLf)分割行,修改某一行(数组的某个元素),Join连接,print #写文件
      

  2.   

    Private Sub Command2_Click()
        Dim s() As String
        Dim Index As Long
        Dim LineID As Long
        Dim CharID As Long
        Dim sLine As String
        Dim sChar As String
        
        Open App.Path & "\1.txt" For Input As #1
        Index = 0
        Do While Not EOF(1)
            ReDim Preserve s(Index)
            Line Input #1, s(Index)
            Index = Index + 1
        Loop
        Close #1
        
        LineID = 1  '你要的行数
        CharID = 3  '你要的字符号
        sChar = "a" '你要插入的字符
        
        sLine = s(LineID - 1)
        
        s(LineID - 1) = Left(sLine, CharID) & sChar & Right(sLine, Len(sLine) - CharID)
        
        Open App.Path & "\1.txt" For Output As #1
        For Index = 0 To UBound(s)
            Print #1, s(Index) & vbCr
        Next Index
        Close #1
        
    End Sub
      

  3.   

    如果是我我会将文本内部所有东西一并提出,第几行可以用SPLIT分解chr(13)就是你的行号,再从指定的行中搜索出符合你条件的字符位置,插入,将此行返回到总字符串中,重新写个文件