【问题标题】:Excel VBA Check if directory exists errorExcel VBA 检查目录是否存在错误
【发布时间】:2013-03-06 23:59:52
【问题描述】:

我有一个电子表格,单击按钮后,它将通过将所有内容复制/粘贴到新工作簿来复制自身,并使用取决于某些变量值的名称保存文件(取自电子表格上的单元格)。 我目前的目标是让它根据客户名称的名称(保存在变量中的单元格值)将工作表保存在不同的文件夹中,虽然这在第一次运行时有效,但之后出现错误。

代码检查目录是否存在,如果不存在则创建它。 这可行,但是在创建之后,再次运行它会引发错误:

运行时错误 75 - 路径/文件访问错误。

我的代码:

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 返回一个零长度的字符串。所以不要使用 Empty 使用 "" 代替
  • 大家好,感谢您的建议,我已将其更改为“”,我从来不知道它会检查零长度字符串。虽然我将把它用于未来的最佳实践,但它并没有解决问题。还有什么建议吗?

标签: excel vba file directory


【解决方案1】:

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

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

注意,对于vbDirectoryDir 将返回一个非空字符串,如果指定的路径已经作为目录存在或作为一个文件(前提是该文件没有任何只读、隐藏或系统属性)。您可以使用GetAttr 来确定它是目录而不是文件。

【讨论】:

  • 嗨,布赖恩,非常感谢您的帮助。我认为这是比较非值的逻辑问题。我很感激:)
  • 当路径是(只是)网络共享时失败(= 返回“”),例如“\\myServer\myShare”。
  • 当路径包含 unicode 字符时失败(= 返回 "")。但 ozmike 的解决方案有效。
【解决方案2】:

使用Scripting 对象的FolderExists 方法。

Public Function dirExists(s_directory As String) As Boolean
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    dirExists = oFSO.FolderExists(s_directory)
End Function

【讨论】:

  • 最干净,最有效的方法!为这个点赞!
  • 看起来是非常一致的方法。我只会为那些采用使用Option Explicit的最佳实践的人添加Dim OFSO As Object
  • 对于那些好奇的人FileSystemObject docs
【解决方案3】:

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

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

它既可以使用,也可以使用\ 结尾和没有。

【讨论】:

  • 你能解释一下你的代码的第三行吗?如何评估这个函数?
  • @wotter - 您可以使用Err.NumberErr.Description 自行检查。我能够得到数字 3 和 53。我认为有几个错误代码正是我选择不为不同的错误号指定 If 条件的原因。基本上,只有一种情况让您感到高兴 - 当您提供正确的目录地址字符串时,显然您会检查该地址,以防函数导致可能不正确的False
  • ozmike's answer 看起来更优雅。
  • @ZygD 事实上,我想知道当出现错误时你是否会得到一个 False 。我的理解是,在这种情况下,FolderExists = 没有被执行,所以它可能具有 True 或 False 以外的值,也许?! (我问是因为我有这样的情况,我的布尔值有一个未定义的值)。所以我建议将 FolderExists 初始化为 False。
  • 我明白你的意思。值得考虑。就我的测试而言,即使随后使用不正确和正确的路径启动它,我也会得到 False,反之亦然。显然,该函数最初以 False 值开始,每次调用时都会重新初始化。我不喜欢这种诉诸错误的逻辑,但在当时这似乎是最好的选择。
【解决方案4】:

我最终使用了:

Function DirectoryExists(Directory As String) As Boolean
    DirectoryExists = False
    If Len(Dir(Directory, vbDirectory)) > 0 Then
        If (GetAttr(Directory) And vbDirectory) = vbDirectory Then
            DirectoryExists = True
        End If
    End If
End Function

这是@Brian 和@ZygD 答案的混合。我认为@Brian 的回答不够,不喜欢@ZygD 的回答中使用的On Error Resume Next

【讨论】:

  • Dir(Directory, vbDirectory) 返回“.”当Directory 为空时。
  • 这行得通。 @KalenGi 这意味着当前目录存在并且其中的第一个文件是“。” (参考 MS-DOS 目录列表)。
  • """//" 被传递时,这会挂起。这个答案是最好的:stackoverflow.com/questions/15480389#41434560
【解决方案5】:
If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
   MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If

【讨论】:

    【解决方案6】:

    这是最干净的方式...到目前为止:

    Public Function IsDir(s) As Boolean
        IsDir = CreateObject("Scripting.FileSystemObject").FolderExists(s)
    End Function
    

    【讨论】:

      【解决方案7】:

      您可以将 WB_parentfolder 替换为“C:\”之类的内容。对我来说 WB_parentfolder 正在获取当前工作簿的位置。 file_des_folder 是我想要的新文件夹。这会根据需要创建尽可能多的文件夹。

              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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-19
        • 2012-09-12
        • 1970-01-01
        相关资源
        最近更新 更多