Forumbeitrag
Excel-Version des Fragestellers:
2022
Erfahrungslevel des Fragestellers:
Excel gut - VBA gut
... irgendwo hatte ich im Hinterkopf, dass man ps auch direkt mit bypass -command verwenden kann ;-)
Darüber habe ich - ehe ich bei mir lange suche - gleich mal mit dem Copilot von GPT geChattet oder wie die da alle heißen und auch eine Lösung bekommen ...
Diese hier noch ohne exclude ;-) - siehe Zusatz weiter unten. Die ist auch rekursiv, d.h. man müsste das -Recurse ggf. (r)ausbauen.
Sub SearchAndOpenFiles()
Dim psCommand As String
Dim wsh As Object
Dim execObj As Object
Dim line As String
Dim searchPath As String
Dim searchPattern As String
Dim fDialog As FileDialog
Dim fileCount As Long
' === Suchmuster festlegen ===
searchPattern = "*abc*.xls*" ' Suchmuster anpassen
' === Ordnerauswahl-Dialog ===
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog
.Title = "Bitte Suchordner auswählen"
.AllowMultiSelect = False
If .Show <> -1 Then
MsgBox "Suche abgebrochen.", vbInformation
Exit Sub
End If
searchPath = .SelectedItems(1)
End With
' === PowerShell-Befehl ===
' Gibt nur vollständige Dateipfade aus
psCommand = "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command " & _
"""Get-ChildItem -Path '" & searchPath & "' -Filter '" & searchPattern & "' -File -Recurse | " & _
"Select-Object -ExpandProperty FullName"""
' === PowerShell starten ===
Set wsh = CreateObject("WScript.Shell")
Set execObj = wsh.Exec(psCommand)
' === Jede gefundene Datei öffnen ===
fileCount = 0
Do While Not execObj.StdOut.AtEndOfStream
line = Trim(execObj.StdOut.ReadLine)
If Len(line) > 0 Then
fileCount = fileCount + 1
On Error Resume Next
Workbooks.Open Filename:=line, ReadOnly:=True
If Err.Number <> 0 Then
MsgBox "Fehler beim Öffnen: " & line, vbExclamation
Err.Clear
End If
On Error GoTo 0
End If
Loop
' === Ergebnis-Info ===
If fileCount = 0 Then
MsgBox "Keine Dateien gefunden.", vbInformation
Else
MsgBox fileCount & " Dateien geöffnet.", vbInformation
End If
End Sub
Für den Ausschluss von Mustern könnte das ps so aussehen:
psCommand = "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command " & _
"""Get-ChildItem -Path '" & searchPath & "' -Filter '" & searchPattern & "' -File -Recurse | " & _
"Where-Object { $_.Name -notmatch '" & excludePattern & "' } | " & _
"Select-Object -ExpandProperty FullName"""
Der Unterschied zu Ralf's Variante ist, dass die Files mit dem Suchstring schon in der Zeile mit Get-ChildItem ... stärker reduziert werden und deshalb bei Where nur noch der unerwünschte Rest ausgeschlossen wird.
(der excludePattern muss natürlich auch zuvor definiert werden ...)