Option Explicit
Public Sub DOSThroughVBA()
Dim i As Long
Dim WScript As Object
Dim strPath As String, strCommand As String
Dim varList As Variant, varFilt As Variant, varPRS As Variant
Range("A:C").ClearContents
Set WScript = CreateObject("WScript.Shell")
On Error Resume Next
'Navigate to folder of which you need listing
strPath = CreateObject("Shell.Application").BrowseForFolder _
(0, "Select Folder For Listing", 0, "").Self.Path
On Error GoTo 0
If strPath = vbNullString Then MsgBox "No Folders Selected!", vbCritical: Exit Sub
'build dir based command for execution
strCommand = "cmd /c dir /s " & Chr(34) & strPath & Chr(34)
'Execute DOS command & get output in array
varList = Split(WScript.Exec(strCommand).StdOut.ReadAll, vbCrLf)
'Filter out unwanted data from array
varFilt = Filter(varList, "<DIR>", False, vbTextCompare)
ReDim varPRS(UBound(varFilt) - 3, 2)
For i = LBound(varFilt) + 2 To UBound(varFilt) - 3
'Replacing these recursive words
If InStr(varFilt(i), " Directory of ") > 0 Then
varPRS(i, 0) = Replace(varFilt(i), " Directory of ", vbNullString)
'Repositioning summary column
ElseIf InStr(varFilt(i), " File(s) ") > 0 Then
varPRS(i, 2) = varFilt(i)
ElseIf IsDate(Mid(varFilt(i), 1, 20)) Then
varPRS(i, 2) = Mid(varFilt(i), 1, 20) 'Date
varPRS(i, 1) = Round(Abs(Mid(varFilt(i), 21, 18)) / 1024, 2) 'Size in KB
varPRS(i, 0) = Mid(varFilt(i), 39, Len(varFilt(i)) - 39) 'FileName
Else
'Rest of the data comes in as it is!
varPRS(i, 0) = varFilt(i)
End If
Next i
Range("A1").Resize(UBound(varPRS), 3) = varPRS
End Sub