![](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_unique_001.png)
![テキストファイル「sample.txt」の内容(ソートされていない、かつ重複行あり)](https://excel-vba.work/wp-content/uploads/2022/11/vba_textfile_sort_unique_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 -Unique "
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/11/vba_textfile_sort_unique_003.png)
![実行結果②](https://excel-vba.work/wp-content/uploads/2022/11/vba_textfile_sort_unique_004.png)
参考①
上記のVBAコードは以下の記事を参考にして作成しました。
参考②
上記で使用した以下の詳細は、公式サイトをご確認ください。
●Power Shellのコマンドレット「Get-Content」
●Power Shellのコマンドレット「Sort-Object」
●Power Shellのコマンドレット「Out-File」