如何使用VBA将文本插入到文本文件中

时间:2014-10-23 13:08:08

标签: vba

我想在" utf-8"的文本文件中的特定位置插入一个字符串。格式。

让我们说文件中的内容是" 12367890"

现在我要插入" 45"在" 3"之后即在第3位,

现在文件中的内容变为" 1234567890"

我写了一些但却无法正常工作

dim str as string 
Dim binaryObj As Object

str = "12367890"

Set binaryObj = CreateObject("adodb.stream")
binaryObj.Open
binaryObj.Charset = "UTF-8"
binaryObj.Type = 2
h = 0
For h = 0 To length
    jpByte = Mid(jpString, h + 1, 1)
    binaryObj.WriteText jpByte
Next
binaryObj.WriteText ChrW(0)
binaryObj.Position = 6
binaryObj.WriteText "4"
binaryObj.Position = 7
binaryObj.WriteText "5"

binaryObj.SaveToFile "D:\A4\Message_tool\withBom.bin", adSaveCreateOverWrite

不是插入4和5,而是将它们替换为6& 5。 7。 输出=" 12345890"

2 个答案:

答案 0 :(得分:0)

正如您可能已经猜到的那样,“WriteText”会覆盖该位置的文本,而不是插入。相反,将所有内容写入新字符插入点(在“3”之后),写入“4”和“5”,然后输出其余内容。

您可能会发现将文件读入字符串更容易,然后使用内置字符串函数操作字符串,然后输出到文件,而不是操作文本文件。

答案 1 :(得分:0)

您可以使用修改后的文本创建临时文件并替换此现有文件。这是一个概念证明。

Public Sub TextFileModify()

    Dim fso As New FileSystemObject
    Dim text As String, line As String, temp As String
    Dim path As String, fs As TextStream, fs2 As TextStream

    'First create a text file with original content
    path = fso.BuildPath(fso.GetSpecialFolder(2), "textfile.txt")
    Set fs = fso.CreateTextFile(path, True)
    fs.WriteLine "12367890"
    fs.WriteLine "other stuff"
    fs.Close

    'Now open the file to replace a line of text
    temp = fso.BuildPath(fso.GetSpecialFolder(2), fso.GetTempName())
    Set fs = fso.OpenTextFile(path, ForReading)
    Set fs2 = fso.CreateTextFile(temp)
    While Not fs.AtEndOfStream
        If fs.line = 1 Then
            line = fs.ReadLine
            fs2.WriteLine Left(line, 3) & "45" & Mid(line, 4)
        Else
            fs2.WriteLine fs.ReadLine
        End If
    Wend
    fs.Close
    fs2.Close

    'New delete old file and replace with new file
    fso.DeleteFile path
    fso.MoveFile temp, path

    ' textfile.txt now contains "1234567890" in the first line and the rest of the file is identical

End Sub

注意:

  • 您必须添加对Microsoft Scripting Runtime的引用(每个Example here
  • fso.GetSpecialFolder(2)返回临时文件夹的路径。
  • fso.GetTempName()会返回radA5FC8.tmp
  • 等文件名