![](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のコマンドレットを実行
することで実現します!
VBAコード
ここでは例として
・デスクトップ配下のテキストファイル「sample.txt」をソート
します。
![テキストファイル「sample.txt」](https://excel-vba.work/wp-content/uploads/2022/11/vba_textfile_sort_001.png)
![](https://excel-vba.work/wp-content/uploads/2022/11/vba_textfile_sort_002.png)
Option Explicit
Sub sample()
Dim targetFile As String
Dim psCommand As String
Dim wsh As Object
Dim result As Integer
'対象ファイル
targetFile = "C:\Users\user\Desktop\sample.txt"
'PowerShellのコマンドレットを組み立て
psCommand = "powershell -NoProfile -ExecutionPolicy Unrestricted "
psCommand = psCommand & "(Get-Content " & targetFile & ") | Sort-Object | 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/11/vba_textfile_sort_003.png)
![実行結果②](https://excel-vba.work/wp-content/uploads/2022/11/vba_textfile_sort_004.png)
参考①
上記のVBAコードは以下の記事を参考にして作成しました。
参考②
上記で使用した以下の詳細は、公式サイトをご確認ください。
●Power Shellのコマンドレット「Get-Content」
●Power Shellのコマンドレット「Sort-Object」
●Power Shellのコマンドレット「Out-File」