繁体   English   中英

使用VBA移动光标以写入文本文件的特定行

[英]Move cursor to write in specific line of a text file with VBA

我想知道如何使用VBA将文本文件的特定行替换为另一文本,以及如何通过移动光标来写入文本文件的特定区域。

这个怎么样:

Dim TextString As Variant
  'read text from file
TextString = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\sometext.txt").ReadAll, Chr(13) & Chr(10))

  'change your text here as TextString(#Line - 1) = "Text"
  'still assume you want to replace line 5
TextString(4) = "New Text"

  'write back in file
CreateObject("Scripting.FileSystemObject").CreateTextFile("C:\sometext.txt").Write (Join(TextString, Chr(13) & Chr(10)))

我认为这很简单,因为只有一行可以读取,而另一行可以写入。 没有循环或关闭文件之类的东西。

您需要自己跟踪位置并相应地应用逻辑。

像这样:

Dim text As String, allText As String
Dim lineNumber As Integer

' Open read handle.
Open "C:\sometext.txt" For Input As #1

allText = ""
lineNumber = 0
Do Until EOF(1)
    lineNumber = lineNumber + 1
    Line Input #1, text

    ' Assume you want to replace line 5.
    If lineNumber = 5 Then
        text = "My new value"
    End if

    allText = allText & vbCrLf & text
Loop

' Close read handle.
Close #1


' Output the new text to a separate file.
Open "C:\updatedtext.txt" For Append As #1
Write #1, allText
Close #1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM