Nahradiť text v textovom súbore pomocou jazyka VBA v programe Microsoft Excel

Obsah

Nasledujúce makrá je možné použiť na nahradenie textu v textovom súbore,
napr. keď chcete zmeniť oddeľovač stĺpcov v textovom súbore
pred importovaním do pracovného hárka programu Excel alebo po exportovaní pracovného hárka do textového súboru.

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 / premenujte súbor a skúste to znova. ", _ 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 & "…" Kým nie je EOF (F1) Ak i Mod 100 = 0, potom Application.StatusBar = _ "Čítací riadok #" & i & "v" & _ TargetFile & "…" Riadkový vstup #F1, tLine Ak sText "" Potom ReplaceTextInString tLine, sText, rText Koniec Ak tlač #F2, tLine i = i + 1 Wend Application.StatusBar = "Zatváranie súborov …" Zatvoriť F1 Zavrieť F2 Zabiť SourceFile 'odstrániť alebo názov pôvodného súboru TargetFile As SourceFile 'premenuje dočasný súbor 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)) Ak p> 0, potom nahraďte SearchString ReplaceString NewString = "" ak p> 1, potom NewString = stred (SourceString, 1, p - 1) NewString = NewString + ReplaceString NewString = NewString + Stred (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", "|", ";" 'nahrádza všetky znaky písmena (|) bodkočiarkami (;) Koncový podbod

Vám pomôže rozvoju miesta, zdieľať stránku s priateľmi

wave wave wave wave wave