使用VBA从Network调用批处理文件

时间:2016-02-04 09:31:47

标签: vba batch-file ms-access access-vba

我有一个访问数据库,我希望从其他用户的共享驱动器中完全运行,并将VBA写入FrontEnd表单。

作为其中一个函数的一部分,它使用VBA调用批处理文件,将其他文件压缩为文本文件,然后将其链接并导入数据库。

但是,由于将数据库移动到共享驱动器以及批处理文件,因此无法找到批处理文件,因为CMD表示不支持UNC路径。理想情况下,我希望VBA在继续使用VBA之前等待批处理文件完成,因为我目前还有另一个使代码等待一段时间的函数(WaitFor(10))。

CMD声称“U:\ My”未被识别为内部或外部命令。这是在VBA编码还是批处理文件中?

关注的代码:

Dim txtPath, batpath, FormDate, tempPath As String

FormDate = Format(Now(), "yyyymmdd")
batpath = Application.CurrentProject.Path & "\Compressor\"
txtPath = Application.CurrentProject.Path & "\Data_TextFile\"
tempPath = Application.CurrentProject.Path & "\TempTextFlows\"

'Do files exist in temp folder?
If Dir(tempPath & "*.*") = "" Then

    'If files don't exist change status to:
  Me.Text41 = "No File(s) Found"
  Else

   'If files do exist change status to:
  Me.Text41 = "Compressing Files, Please Wait..."

   'Call the Files compressor
  Call Shell(Environ$("COMSPEC") & " /c " & batpath & "myBat.bat", vbNormalFocus)

   'Wait 5 seconds for flow compressor to run
  Call WaitFor(10)

   'Link text file created by flow compressor using "TextFile_" and todays date
  DoCmd.TransferText acLinkDelim, "TextFile20160126 Link Specification", _
 "TextFile_" & FormDate, txtPath & "TextFile_" & FormDate & ".txt"

   'Format recently linked FormatTextFlows into tables
  Call FormatTextFlows
  Me.Text41 = "Files Completed"

End If

以下是它调用的批处理文件:

U:
cd "My Folder\test\FormatTextFlows\TempTextFlows"

echo Date format = %date%
echo dd = %date:~0,2%
echo mm = %date:~3,2%
echo yyyy = %date:~6,4%
echo.
echo Timestamp = %date:~6,4%-%date:~3,2%-%date:~0,2%

copy *.USR "My Folder\test\FormatTextFlows\Data_TextFile\TextFile_%date:~6,4%%date:~3,2%%date:~0,2%.txt"

提前感谢任何人提供的任何帮助。

2 个答案:

答案 0 :(得分:1)

如果有空格,则需要引号:

U:
cd "My Folder\test\FormatTextFlows\TempTextFlows"

但是使用这个,我想这应该是:

copy *.USR "U:\My Folder\test\FormatTextFlows\Data_TextFile\TextFile_%date:~6,4%%date:~3,2%%date:~0,2%.txt"

您可能还需要Shell命令中的引号:

Call Shell(Environ$("COMSPEC") & " /c " & Chr(34) & batpath & "myBat.bat" & Chr(34), vbNormalFocus)

调试:

'Link text file created by flow compressor using "TextFile_" and todays date
Debug.Print "TextFile20160126 Link Specification", _
"TextFile_" & FormDate, txtPath & "TextFile_" & FormDate & ".txt"
DoCmd.TransferText acLinkDelim, "TextFile20160126 Link Specification", _
"TextFile_" & FormDate, txtPath & "TextFile_" & FormDate & ".txt"

检查Shell调用:

Debug.Print Environ$("COMSPEC") & " /c " & Chr(34) & batpath & "myBat.bat" & Chr(34)
Call Shell(Environ$("COMSPEC") & " /c " & Chr(34) & batpath & "myBat.bat" & Chr(34), vbNormalFocus)

答案 1 :(得分:1)

我设法通过阅读微软的网站(https://support.office.com/en-us/article/shell-function-ff2e4b1b-712d-4e34-aea6-6832eadd3c63)解决了这个问题。所以我用Call Shell(Environ$("COMSPEC") & " /c " & batpath & "myBat.bat", vbNormalFocus)Dim UtilShell

替换了行UtilShell = Shell(batpath & "D0301.bat", vbHide)