excel - VBA检查文件是否存在

标签 excel vba file exists file-exists

我有这个代码。它应该检查文件是否存在,如果存在则打开它。如果文件存在,它确实有效,如果不存在,但是,每当我将文本框留空并单击提交按钮时,它都会失败。如果文本框为空,我想要的是显示错误消息,就像文件不存在一样。

Runtime-error "1004"

Dim File As String
File = TextBox1.Value
Dim DirFile As String

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & File
If Dir(DirFile) = "" Then
  MsgBox "File does not exist"
Else
    Workbooks.Open Filename:=DirFile
End If

最佳答案

类似这样的事情

最好使用工作簿变量来提供对打开的工作簿的进一步控制(如果需要)

已更新以测试文件名是实际的工作簿 - 这也使得初始检查变得多余,除了向用户发送消息文本框为空

Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile
If Len(Dir(DirFile)) = 0 Then
  MsgBox "File does not exist"
Else
 On Error Resume Next
 Set WB = Workbooks.Open(DirFile)
 On Error GoTo 0
 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If

关于excel - VBA检查文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16351249/

相关文章:

java - 递归压缩一个目录,其中包含 Java 中任意数量的文件和子目录?

vba - AppActivate返回Excel

excel - 如何保存在“另存为”对话框中选择的文件?

vba - 将多个单元格链接到 TextBox VBA

vba - 什么是运行时错误 91?为什么它会出现在我的 Excel VBA 脚本中?

java - 使用 Java 复制文件时结果为空

c - inotify 事件 IN_MODIFY 为 tftp put 发生两次

java - 如何使用java在selenium中将结果输入到excel文件中

excel - 删除 Excel 表格中的所有数据行(第一行除外)

javascript - 如何在网页上找到按钮