VBA如何获取CMD命令的运行结果

图(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变量的值即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TOMaster.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值