shell - Excel VBA : Running a shell script to both change directory and then run a custom script

标签 shell excel csv vba

我正在尝试使用 vba 运行此 cmd 脚本,该脚本基本上合并目录中的所有 csv 文件,然后将每个文件的文件名添加到末尾的列中。

for /f %a in ('dir /b *.csv') do for /f "tokens=*" %b in (%a) do echo %b,%a >> all.csv

我遇到的问题是如何在 Excel Vba 中运行此命令,同时在运行上述代码之前更改默认目录。

这是因为 for/f %a in ('dir/b *.csv') 位仅采用 cmd 窗口中的默认目录。在实际的 cmd 窗口中,我只能使用 cd 命令,但不知道如何使用 vba 自动执行此操作。

Link to the original post for the code

大家有什么想法吗?

谢谢

最佳答案

这是一种从 VBA Excel 运行代码的方法。我对路径进行了硬编码,因为我不确定您的输入法是什么。

Sub mergeCSV()
    Dim myDir As String
    myDir = "C:\Users\username\compile\"

    Dim strCommand As String
    strCommand = "for /f %a in ('dir /b *.csv') do for /f ""tokens=*"" %b in (%a) do echo %b,%a >> all.csv"

    Call Shell("cmd.exe /k cd /d " & myDir & " & " & strCommand, 1)
End Sub

Shell 调用首先打开命令提示符,然后将当前目录更改为 myDir 变量中指定的目录。然后它运行第二个命令,我将其放入它自己的变量 strCommand 中,以使其更易于阅读和遵循。您可以通过将 /k 替换为 /c

来使窗口不会保持打开状态

我有两个文件用于测试,一个包含数字,另一个包含字母字符。结果文件 all.csv 看起来像这样:

enter image description here

关于shell - Excel VBA : Running a shell script to both change directory and then run a custom script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860412/

相关文章:

shell - 如何使用Shell脚本在dockerfile中的环境变量中设置动态值

shell - 执行 KornShell 脚本

mysql - 没有 shell 的复制 MySQL 数据库

regex - 当一个模式是 bash/awk 中的变量时如何在两种模式之间取线(动态正则表达式)

excel - 合并唯一列上的值

Excel 2013 VBA 运行时错误 13 类型不匹配

使用两个日期的 SQL 查询

python - Pandas 正确打印到屏幕,但仅将一些数据保存到 csv

java - 使用 Commons CSV 解析 CSV - 引号内的引号导致 IOException

python - 通过Python CSV到SQL : passing multiple arguments