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

时间:2015-07-08 13:56:34

标签: excel vba excel-vba

我想知道如何使用VBA用另一个文本替换文本文件的特定行,并通过移动光标在文本文件的特定区域中写入。

2 个答案:

答案 0 :(得分:2)

这个怎么样:

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)))

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

答案 1 :(得分:0)

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

这样的事情:

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