我试着通过阅读你的论坛来教育自己一段时间关于VBA的知识,并希望你现在能帮我解决一个我找不到的错误。
我试图在关闭时保存一个工作簿。该文件路径是一个映射驱动器,但是,没有该驱动器的访问权限的人可能会使用该文件。因此,当找不到文件路径并退出该文件时,我希望宏什么也不做。这就是我获得运行时错误的地方。有什么建议吗?
代码:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim OrigName As String
Dim FolderPath As String
OrigName = ActiveWorkbook.FullName
FolderPath = "\\MappedDrive\Folder1\Folder2\"
If Dir(FolderPath, vbDirectory) <> vbNullString Then
ActiveWorkbook.SaveAs FolderPath + ActiveWorkbook.Name
ActiveWorkbook.SaveAs OrigName
Else
Exit Sub
End If
End Sub当连接到驱动器时,代码运行良好,但一旦断开连接,我将得到以下行的错误消息:
If Dir(FolderPath, vbDirectory) <> vbNullString Then消息:运行时错误52:错误文件名我们的编号
如前所述,如果找不到文件路径,我希望代码中止并关闭工作簿,就像不存在宏一样。
提前感谢!
发布于 2019-05-21 14:19:59
可以尝试使用错误处理:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim OrigName As String
Dim FolderPath As String
OrigName = ActiveWorkbook.FullName
FolderPath = "\\MappedDrive\Folder1\Folder2\"
on error goto finish
ActiveWorkbook.SaveAs FolderPath + ActiveWorkbook.Name
ActiveWorkbook.SaveAs OrigName
on error goto 0
' continue code here if you need to do more
finish:
' you can add code here that will be performed if the error occurs
End Sub发布于 2019-05-21 14:23:35
这是不存在的驱动器的预期功能 of Dir:
Debug.Print Dir("\\ValidDrive\ValidFolder", vbDirectory)
'Result: "ValidFolder"
Debug.Print Dir("\\ValidDrive\InValidFolder", vbDirectory)
'Result: ""
Debug.Print Dir("\\InValidDrive\InValidFolder", vbDirectory)
'Result: Runtime Error 52: Bad File Name our Number 要么使用FileSystemObject,要么使用On Error来捕捉这些情况。
https://stackoverflow.com/questions/56237820
复制相似问题