gpt4 book ai didi

excel - VBA检查文件是否存在

转载 作者:行者123 更新时间:2023-12-01 16:37:02 27 4
gpt4 key购买 nike

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

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/

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