使用Dir
方法:
Sub Dir_Use()
Dim i As Long
Dim FileList()
Dim FSO As Object
Dim oFile As Object
Dim strPath As String
strPath = "c:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
FileList = Read_FilesNames_From_Folder(strPath)
Set oFile = FSO.CreateTextFile(strPath)
For i = LBound(FileList) To UBound(FileList)
oFile.WriteLine FileList(i)
Next i
oFile.Save
oFile.Close
Set FSO = Nothing
Set oFile = Nothing
End Sub
Function Read_FilesNames_From_Folder(InitilFolderPath As String) As Variant
With Application
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Dim FileName As String, _
FolderPath As String, _
Results()
ReDim Results(0)
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = InitilFolderPath
If .Show = True Then
FolderPath = .SelectedItems(1)
Else
Exit Function
End If
End With
FileName = Dir(FolderPath & "*.xlsx")
Do While FileName <> ""
Results(UBound(Results)) = FileName
ReDim Preserve Results(UBound(Results) + 1)
FileName = Dir
Loop
ReDim Preserve Results(UBound(Results) - 1)
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
Read_FilesNames_From_Folder = Results
End Function
或者使用您的初始代码,通过 FileDialogFolderPicker 选择文件夹,如下所示:
Sub test_Marcos_Busto()
Dim Dir1 As String
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = "c:\test"
If .Show = True Then
Dir1 = .SelectedItems(1)
Else
Exit Sub
End If
End With
'You don't use Dir1 afterwards... So, I'm not sure where to go afterwards
Order1 = "type *.b*>>mat.txt"
Order2 = "dir/b>lista.txt"
Call Shell("cmd.exe /S /K" & Order1, vbNormalFocus)
Call Shell("cmd.exe /S /K" & Order2, vbNormalFocus)
End Sub