在Excel VBA中创build文件夹时找不到path

我有一个VBA子程序循环通过Excel电子表格的行,并将文件从存储在一个单元格中的path复制到由其他几个单元格的信息组成的path。 大多数情况下需要为文件创build一个文件夹,但只有一个层次更深(而不是尝试)但是,当我运行它时,我有时会得到一个运行时错误76 path not found当我看着Windows中的文件夹资源pipe理器出现该文件夹,但稍微透明(如正在写入的文件)。

为什么我在fso.Createfolder strDirPath这个错误? 我猜这与时间有关,因为当我再次运行脚本时,它可以通过该文件就好了。 有没有办法检查文件夹是否准备好了?

 Sub CopyFiles() ' Copy to location [root_folder]\company_name\contract_no'_'file_name Dim strRootFolder, strCompany, strContract, strFileName, strDirPath Dim strFullPath, strFromPath, intRow strRootFolder = "C:\...\DestinationFolder\" intRow = 2 Dim fso As New FileSystemObject 'Loop through rows Range("C" & 2).Select 'First row to check (column always filled) Do Until IsEmpty(ActiveCell) ' Loop through till end of spreadsheet strFromPath = objSheet.Range("C" & intRow).Value ' Replace "/" characters in company names with "_" strCompany = Replace(objSheet.Range("E" & intRow).Value, "/", "_") strContract = objSheet.Range("A" & intRow).Value & "_" ' Replace "#" in file names with "0" strFileName = Replace(objSheet.Range("B" & intRow).Value, "#", "0") strDirPath = strRootFolder & strCompany & "\" strFullPath = strDirPath & strContract & strFileName ' Create directory if it does not exist If Not fso.FolderExists(strDirPath) Then fso.Createfolder strDirPath ' !!! This is where the error is !!! End If ' Copy file fso.CopyFile strFromPath, strFullPath, False intRow = intRow + 1 ActiveCell.Offset(1, 0).Select ' drop one to check if filled Loop End Sub 

注意:这不是因为目录名称中的反斜杠。 代码replace反斜杠,input中没有正斜杠。

问题是正在创build的目录在一个空间结束。 在Windows资源pipe理器中,如果您创build的文件夹末尾有空格,则会自动修剪名称。 但是,在VBA中不会自动完成。

解决的办法是在您的目录名称周围调用Trim()

  strDirPath = Trim(strRootFolder & strCompany) & "\" 

小费:

尾随空格的文件夹已创build,但会在Windows中引起问题。 要重命名或删除它们,您需要使用带有networkingpath语法的命令行。 (请参阅使用前导空格和尾随空格重命名/删除Windows(x64)文件夹 )

 rename "\\?\c:\<PATH HERE>\ 1 " "<NEW FILE NAME>"