Last active
July 20, 2025 15:36
-
-
Save kinuasa/23e85fbc3e31c657d634b21e6a96430e to your computer and use it in GitHub Desktop.
ドラッグ&ドロップでファイルのパスを取得するVBAマクロ 関連記事:https://note.com/kinuasa/n/n3db79c1b6e03
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Public Sub Sample() | |
| Dim aryPaths As Variant | |
| Dim i As Long | |
| aryPaths = GetDroppedFileAndFolders | |
| If UBound(aryPaths) <> -1 Then | |
| For i = LBound(aryPaths) To UBound(aryPaths) | |
| Debug.Print aryPaths(i) | |
| Next | |
| End If | |
| End Sub | |
| 'ドラッグ&ドロップされたファイルやフォルダーのパスを取得 | |
| Private Function GetDroppedFileAndFolders() As Variant | |
| '実行するPowerShellスクリプト | |
| Dim com As String | |
| com = "PowerShell -WindowStyle Hidden -Command """ | |
| com = com & "Add-Type -AssemblyName \""PresentationFramework\"";" | |
| com = com & "$xaml = '<Window xmlns=\""http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" Title=\""FilePicker\"" Height=\""250\"" Width=\""350\"" AllowDrop=\""True\"" Topmost=\""True\""><Grid><ListBox Name=\""FileListBox\"" AllowDrop=\""True\""/><TextBlock Name=\""HintText\"" Text=\""ここにファイルをドラッグ&ドロップしてください\"" Foreground=\""Gray\"" HorizontalAlignment=\""Center\"" VerticalAlignment=\""Center\"" IsHitTestVisible=\""False\"" /></Grid></Window>';" | |
| com = com & "$reader = [System.Xml.XmlReader]::Create([System.IO.StringReader]$xaml);" | |
| com = com & "$window = [Windows.Markup.XamlReader]::Load($reader);" | |
| com = com & "$fileListBox = $window.FindName(\""FileListBox\"");" | |
| com = com & "$files = @();" | |
| com = com & "$fileListBox.Add_DragOver({if($_.Data.GetDataPresent([Windows.DataFormats]::FileDrop)){$_.Effects = [Windows.DragDropEffects]::Copy}else{$_.Effects = [Windows.DragDropEffects]::None};$_.Handled = $true});" | |
| com = com & "$fileListBox.Add_Drop({if($_.Data.GetDataPresent([Windows.DataFormats]::FileDrop)){$script:files = $_.Data.GetData([Windows.DataFormats]::FileDrop);$window.Close()}});" | |
| com = com & "$window.ShowDialog() | Out-Null;" | |
| com = com & "Write-Host($files -Join \""|\"") -NoNewline;""" | |
| '実行結果を標準出力として取得 | |
| Dim oExec As Object | |
| Set oExec = CreateObject("WScript.Shell").Exec(com) | |
| Do While oExec.Status = 0 | |
| DoEvents | |
| Loop | |
| GetDroppedFileAndFolders = Split(oExec.StdOut.ReadAll, "|") | |
| End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
いみひと氏からコメントをいただき、WindowsTerminalの最小化処理をUI AutomationからPowerShellの"-WindowStyle Hidden"に変更しました。