VBA 检查文件是否存在 [英] VBA check if file exists

查看:32
本文介绍了VBA 检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this code. It is supposed to check if a file exists and open it if it does. It does work if the file exists, and if it doesn't, however, whenever I leave the textbox blank and click the submit button, it fails. What I want, if the textbox is blank is to display the error message just like if the file didn't exist.

运行时错误1004"

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

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

推荐答案

类似这样的事情

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

best to use a workbook variable to provide further control (if needed) of the opened workbook

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

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 SettingsAdministratorDesktop" & 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

这篇关于VBA 检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆