2013-08-14 1 views
2

입력 파일을 반복하면서 각 행을 읽는 readline 명령을 사용하여 다양한 기준을 확인한 다음 결과에 따라 변경하고 싶습니다. 여기에 내가 할 노력하고있어 매우 간단한 버전은 다음과 같습니다VBA에서 FileSystemObject로 연 파일에서 행을 편집하려면 어떻게해야합니까?

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objFile = objFSO.OpenTextFile(strFileLoc, 1) 

Do While Not objFile.AtEndOfStream 
    strLineRead = objFile.readline 
    if strLineRead Like "*text to change*" Then 
      'Some code to change the line 
    end if 
Loop 

내가 내 strLineRead을 대체 할 기능을 대체하여 다음 strFileText라는 문자열로 전체 파일을 저장하고 해왔습니다 변경된 버전의 문자열. 다음과 같은 내용 :

strFileText = Replace(strFileText, strLineRead, strNewLine) 

그런 다음 전체 문자열을 새 텍스트 파일에 씁니다.

문제는 가끔 전체 텍스트가 "NC"인 줄을 한 다음 "NC"의 전체 파일에서 찾기/바꾸기를 한 줄 이상으로 변경하는 것입니다.

FileSystemObject에는 특정 행에서 파일을 직접 변경할 수있는 명령이 있습니까? 나는 "writeline"명령과 같은 것을 생각하고있다.

답변

1

파일과 이벤트의 개인용 잠수정을 가지고 전화하십시오. 먼저 replace_text를 호출하고 요구 사항을 채 웁니다. 내 샘플 코드를 참조하십시오.

Private Sub Command3_Click() 

    Dim sFileName As String 
    Dim fileSys As Variant 

    ' Edit as needed 
    sFileName = Me.FileList.Value 

    Set fileSys = CreateObject("Scripting.FileSystemObject") 

    Replace_Text sFileName, "bad text", "good text", fileSys 
    End Sub 
    Private Sub Replace_Text(targetFile As String, targetText As String, replaceText As String, fileSys As Variant) 
    If Right(targetFile, 3) = "filepath extension you want (example: xml or doc etc.)" Then 
     Update_File targetFile, targetText, replaceText, fileSys 
    Else 
     MsgBox "You did not select the right file. Please try again." 
    End If 
    End Sub 
    Private Sub Update_File(fileToUpdate As String, targetText As String, replaceText As String, fileSys As Variant) 

    Dim tempName As String 
    Dim tempFile As Variant 
    Dim file As Variant 
    Dim currentLine As String 
    Dim newLine As String 


     'creates a temp file and outputs the original files contents but with the replacements 
     tempName = fileToUpdate & ".tmp" 
     Set tempFile = fileSys.CreateTextFile(tempName, True) 

     'open the original file and for each line replace any matching text 
     Set file = fileSys.OpenTextFile(fileToUpdate) 
     Do Until file.AtEndOfStream 
      currentLine = file.ReadLine 
      newLine = Replace(currentLine, targetText, replaceText) 
      'write to the new line containing replacements to the temp file 
      tempFile.WriteLine newLine 
     Loop 
     file.Close 

     tempFile.Close 

     'delete the original file and replace with the temporary file 
     fileSys.DeleteFile fileToUpdate, True 
     fileSys.MoveFile tempName, fileToUpdate 
    End Sub 
+0

그래서 WriteLine 명령이있는 것처럼 보이지만 현재 읽혀지고있는 파일이 아닌 파일의 별도 사본에 기록되어야합니다. –

+0

아니 완벽하게 작동합니다. 그냥 임시 파일에 쓴 다음 원본 파일로 변환합니다. –

+0

마이클이 당신을 위해이 일을 했습니까? –

관련 문제