Excel VBA检查目录是否存在错误

我有一个电子表格,点击一个button将复制自己复制/粘贴到新的工作簿,并保存与依赖于一些variables值(取自电子表格单元格)的名称的文件。 我目前的目标是让它根据客户端名称(单元格值保存在variables)的名称保存在不同的文件夹中,而这在第一次运行时,我得到一个错误之后。

代码将检查目录是否存在,如果不存在则创build它。 这工作,但创build后,第二次运行它会引发错误:

运行时错误75 – path/文件访问错误。

我的代码:

Sub Pastefile() Dim client As String Dim site As String Dim screeningdate As Date screeningdate = Range("b7").Value Dim screeningdate_text As String screeningdate_text = Format$(screeningdate, "yyyy\-mm\-dd") client = Range("B3").Value site = Range("B23").Value Dim SrceFile Dim DestFile If Dir("C:\2013 Recieved Schedules" & "\" & client) = Empty Then MkDir "C:\2013 Recieved Schedules" & "\" & client End If SrceFile = "C:\2013 Recieved Schedules\schedule template.xlsx" DestFile = "C:\2013 Recieved Schedules\" & client & "\" & client & " " & site & " " & screeningdate_text & ".xlsx" FileCopy SrceFile, DestFile Range("A1:I37").Select Selection.Copy Workbooks.Open Filename:= _ "C:\2013 Recieved Schedules\" & client & "\" & client & " " & site & " " & screeningdate_text & ".xlsx", UpdateLinks:= _ 0 Range("A1:I37").PasteSpecial Paste:=xlPasteValues Range("C6").Select Application.CutCopyMode = False ActiveWorkbook.Save ActiveWindow.Close End Sub 

你不得不原谅我在这方面的知识不足,我还在学习。 我有一个非常强烈的感觉,它与目录检查逻辑有关,因为当错误被抛出时, MkDir行被突出显示。

要使用Dir检查目录是否存在,需要将vbDirectory指定为第二个参数,如下所示:

 If Dir("C:\2013 Recieved Schedules" & "\" & client, vbDirectory) = "" Then 

请注意,使用vbDirectory ,如果指定的path已经作为目录或作为文件存在 (如果该文件没有任何只读属性,隐藏属性或系统属性),则Dir将返回一个非空string。 你可以使用GetAttr来确定它是一个目录而不是一个文件。

使用脚本对象的FolderExists方法。

 Public Function dirExists(s_directory As String) As Boolean Set OFSO = CreateObject("Scripting.FileSystemObject") dirExists = OFSO.FolderExists(s_directory) End Function 
 If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY" End If 

要确定文件夹存在(而不是文件 ),我使用这个函数:

 Public Function FolderExists(strFolderPath As String) As Boolean On Error Resume Next FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory) On Error GoTo 0 End Function 

它既可以工作,也可以工作。

你可以用“C:\”来代替WB_parentfolder。 对我来说,WB_parentfolder抓取当前工作簿的位置。 file_des_folder是我想要的新文件夹。 这会通过并根据需要创build尽可能多的文件夹。

  folder1 = Left(file_des_folder, InStr(Len(WB_parentfolder) + 1, file_loc, "\")) Do While folder1 <> file_des_folder folder1 = Left(file_des_folder, InStr(Len(folder1) + 1, file_loc, "\")) If Dir(file_des_folder, vbDirectory) = "" Then 'create folder if there is not one MkDir folder1 End If Loop 

我结束了使用:

 Function DirectoryExists(Directory As String) As Boolean DirectoryExists = False If Not Dir(Directory, vbDirectory) = "" Then If GetAttr(Directory) And vbDirectory = vbDirectory Then DirectoryExists = True End If End If End Function 

这是@Brian和@ZygD答案的组合。 在那里我认为@Brian答案是不够的,不喜欢@ZygD答案的“在错误恢复下一个”