Nahraďte text v textovém souboru pomocí VBA v Microsoft Excelu

Obsah

Níže uvedená makra lze použít k nahrazení textu v textovém souboru,
např. když chcete změnit oddělovač sloupců v textovém souboru
před importem do listu aplikace Excel nebo po exportu listu do textového souboru.

Sub ReplaceTextInFile (SourceFile As String, _ sText As String, rText As String) Dim TargetFile As String, tLine As String, tString As String Dim p As Integer, i As Long, F1 As Integer, F2 As Integer TargetFile = "RESULT.TMP "If Dir (SourceFile) =" "Then Exit Sub If Dir (TargetFile)" "Then On Error Resume Next Kill TargetFile On Error GoTo 0 If Dir (TargetFile)" "Then MsgBox TargetFile & _" already open, close and delete / přejmenujte soubor a zkuste to znovu. ", _ vbCritical Exit Sub End If End If F1 = FreeFile Open SourceFile For Input As F1 F2 = FreeFile Open TargetFile For Output As F2 i = 1 'line counter Application.StatusBar =" Reading data from " & _ TargetFile & "…" zatímco není EOF (F1) Pokud i Mod 100 = 0, pak Application.StatusBar = _ "Čtecí řádek #" & i & "v" & _ TargetFile & "…" Line Input #F1, tLine If sText "" Potom ReplaceTextInString tLine, sText, rText End If Print #F2, tLine i = i + 1 Wend Application.StatusBar = "Zavírání souborů …" Zavřít F1 ​​Zavřít F2 Zabít SourceFile odstranit nebo název původního souboru TargetFile As SourceFile 'přejmenovat dočasný soubor Application.StatusBar = False End Sub Private Sub ReplaceTextInString (SourceString As String, _ SearchString As String, ReplaceString As String) Dim p As Integer, NewString As String Do p = InStr (p + 1 , UCase (SourceString), UCase (SearchString)) Pokud p> 0, pak nahraďte SearchString ReplaceString NewString = "" If p> 1 Then NewString = Mid (SourceString, 1, p - 1) NewString = NewString + ReplaceString NewString = NewString + Mid (SourceString, _ p + Len (SearchString), Len (SourceString)) p = p + Len (ReplaceString) - 1 SourceString = NewString End If If p> = Len (NewString) Then p = 0 Loop until p = 0 End Sub Sub TestReplaceTextInFile () ReplaceTextInFile ThisWorkbook.Path & _ "\ ReplaceInTextFile.txt", "|", ";" 'nahrazuje všechny znaky potrubí (|) středníky (;) End Sub

Vám pomůže rozvoji místa, sdílet stránku s přáteli

wave wave wave wave wave