gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:33:24 25 4
gpt4 key购买 nike

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

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

Runtime Error 75 - path/file access error.

我的代码:

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,如果指定的路径已作为目录或文件存在,Dir 将返回非空字符串或文件(前提是该文件没有任何只读、隐藏或系统属性)。您可以使用 GetAttr 来确定它是一个目录而不是文件。

关于Excel VBA 检查目录是否存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com