
图(1)
CMD命令的特点是简单高效,往往一个复杂的过程只需一行命令就搞定,因此我们在设计VBA程序的时候如果能直接获取CMD命令的运行结果将会事半功倍,下面我给大家演示VBA是如何获取DIR命令的文件列表,代码如下:
Sub GetDirFiles()
'
' 获取CMD命令Dir文件列表
'
Dim strCommand As String
Dim strOutput As String
Dim wshShell As Object
Dim wshExec As Object
Dim fileStyle As String
Dim filePath As String
Dim fileNum As Integer
fileStyle = "txt" ' 设置文件类型
filePath = "D:\Users\Hero\Desktop\办公室" ' 设置文件路径
' 设置要执行的CMD命令
strCommand = "cmd.exe /c dir /a /b /s " & filePath & "\*." & fileStyle
' 创建WScript.Shell对象
Set wshShell = CreateObject("WScript.Shell")
' 执行命令并获取输出
Set wshExec = wshShell.Exec(strCommand)
' 读取命令输出
Do While Not wshExec.StdOut.AtEndOfStream
strOutput = strOutput & wshExec.StdOut.ReadLine() & vbCrLf
fileNum = fileNum + 1
Loop
' 显示输出结果
Debug.Print strOutput
Debug.Print "执行完毕!总共有" & fileNum & "个" & fileStyle & "文件"
' 清理对象和变量
Set wshExec = Nothing
Set wshShell = Nothing
fileNum = 0
End Sub
下面是运行结果:

图(2)
使用以上方法你只需要重新定义filePath和fileStyle变量的值即可。

3879

被折叠的 条评论
为什么被折叠?



