![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBAで
・テキストファイル内の文字列を置換
できます!
![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBAから
・Power Shellのコマンドレットを実行
することで実現します!
※演算子「-creplace」等により実現します。
VBAコード
ここでは例として、
・デスクトップ配下のテキストファイル「sample.txt」内の
・文字列「(株)」を「株式会社」へ置換
します。
![テキストファイル「sample.txt」](https://excel-vba.work/wp-content/uploads/2022/09/vba_textfile_replace_001.png)
![テキストファイル「sample.txt」の内容](https://excel-vba.work/wp-content/uploads/2022/09/vba_textfile_replace_002.png)
Option Explicit
Sub sample()
Dim targetFile As String
Dim beforeStr As String
Dim afterStr As String
Dim psCommand As String
Dim wsh As Object
Dim result As Integer
'対象ファイル
targetFile = "C:\Users\user\Desktop\sample.txt"
'置換前文字列
beforeStr = "\(株\)"
'置換後文字列
afterStr = "株式会社"
'PowerShellのコマンドレットを組み立て
psCommand = "powershell -NoProfile -ExecutionPolicy Unrestricted "
psCommand = psCommand & "(Get-Content " & targetFile & ") -creplace " & "'" & beforeStr & "'" & "," & "'" & afterStr & "'"
psCommand = psCommand & " | Out-File -Encoding default " & targetFile
Set wsh = CreateObject("WScript.Shell")
'PowerShellのコマンドレットを実行
result = wsh.Run(Command:=psCommand, WindowStyle:=0, WaitOnReturn:=True)
If (result = 0) Then
MsgBox ("置換が正常終了しました。")
Else
MsgBox ("置換が異常終了しました。")
End If
'後片付け
Set wsh = Nothing
End Sub
実行結果
テキストファイル内の文字列を置換できました。
※文字列「(株)」を「株式会社」へ置換できました。
![実行結果①](https://excel-vba.work/wp-content/uploads/2022/09/vba_textfile_replace_003.png)
![実行結果②](https://excel-vba.work/wp-content/uploads/2022/09/vba_textfile_replace_004.png)
参考①
上記のVBAコードは以下の記事を参考にして作成しました。
参考②
Excelファイル内の文字列の置換もできます。
詳細は以下の記事をご確認ください。
参考③
上記で使用した以下の詳細は、公式サイトをご確認ください。
●Power Shellのコマンドレット「Get-Content」
●Power Shellの演算子「-creplace」
●Power Shellのコマンドレット「Out-File」