2014-10-23 2 views
1

"utf-8"형식의 텍스트 파일에서 특정 위치에 문자열을 삽입하고 싶습니다.VBA를 사용하여 텍스트 파일에 텍스트를 삽입하는 방법

하자가

이제 파일의 내용이 "1234567890"가, 파일의 내용은 내가 즉, 위치 3에서 "3"이후에 "45"을 삽입 할 지금

"12367890"라고

내가 어떤 작품을 썼다지만 4와 5를 삽입하는 대신

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 

작동하지 않습니다,이 6 & 7. 0123로 대체 뻥된다output = "12345890"

+0

같은 파일 이름은 조회 ['FileSystemObject'] (http://stackoverflow.com/a/5798392/380384) 텍스트 파일을 처리하는 데 사용할 수있는 방법에 대해 설명합니다. – ja72

+0

또한 텍스트 파일의 확장자는'.bin'이어야합니다. – ja72

답변

0

짐작할 수 있듯이 "WriteText"는 삽입하는 대신 해당 위치의 텍스트를 덮어 씁니다. 대신 새로운 문자 삽입 지점 ("3"다음)까지 모든 것을 쓰고 "4"와 "5"를 쓰고 나머지는 출력하십시오.

파일을 문자열로 읽은 다음 문자열 기능을 사용하여 문자열을 조작 한 다음 텍스트 파일을 조작하는 대신 파일로 출력하는 것이 더 쉽습니다.

+0

[중간 $() 함수에 중점을 둔 VBA의 숨겨진 기능] (http://stackoverflow.com/questions/1070863/hidden-features- of-vba) –

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 

참고 :

  • 당신은
  • fso.GetSpecialFolder(2)이 임시 폴더의 경로를 반환합니다. (당 Example here)은 Microsoft 런타임 스크립팅에 대한 참조를 추가해야합니다.
  • fso.GetTempName() 반환 radA5FC8.tmp
+0

수 백 줄이있을 때 어떻게합니까? 모든 파일에 대해 writeline을 사용할 수 없다 : ( –

+0

'WriteLine()'명령은 예제 파일을 만드는 데만 사용되었으며, 원래 파일은'WriteLine()'문으로 하드 코딩 될 가능성이 거의 없다. 그것은 어딘가에서 생성 될 가능성이 더 높고 교체 작업은 단일 행으로만 작동하면됩니다. – ja72

관련 문제