Jos*_*sta 35 excel vba file excel-vba
我有这个代码.它应该检查文件是否存在,如果存在则打开它.如果文件存在,它确实有效,但如果文件不存在,那么每当我将文本框留空并单击提交按钮时,它就会失败.我想要的是,如果文本框为空,则显示错误消息,就像文件不存在一样.
运行时错误"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
Run Code Online (Sandbox Code Playgroud)
bre*_*tdj 53
这样的事情
最好使用工作簿变量来提供打开的工作簿的进一步控制(如果需要)
更新以测试该文件名是一个实际工作簿 - 这也使初始检查冗余,而不是向用户发送消息而不是文本框为空
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
Run Code Online (Sandbox Code Playgroud)
Pat*_*rez 33
我使用此函数来检查文件是否存在:
Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
On Error Resume Next
IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function
Run Code Online (Sandbox Code Playgroud)
Zyg*_*ygD 23
为了检查存在,还可以使用(适用于文件和文件夹):
Not Dir(DirFile, vbDirectory) = vbNullString
Run Code Online (Sandbox Code Playgroud)
结果是True存在文件或目录.
例:
Run Code Online (Sandbox Code Playgroud)If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then MsgBox "exists" Else MsgBox "does not exist" End If
一种干净而简短的方法:
Public Function IsFile(s)
IsFile = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function
Run Code Online (Sandbox Code Playgroud)
Function FileExists(ByRef strFileName As String) As Boolean
' TRUE if the argument is an existing file
' works with Unicode file names
On Error Resume Next
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileExists = objFSO.FileExists(strFileName)
On Error GoTo 0
End Function
Run Code Online (Sandbox Code Playgroud)
为了使函数运行得更快,可以将 objFSO 设为全局变量,然后修改代码并将其保存在模块中,如下所示:
Option Explicit
Dim objFSO As Object
Function FileExists(ByRef strFileName As String) As Boolean
' TRUE if the argument is an existing file
' works with Unicode file names
On Error Resume Next
If objFSO Is Nothing Then Set objFSO = CreateObject("Scripting.FileSystemObject")
FileExists = objFSO.FileExists(strFileName)
On Error GoTo 0
End Function
Run Code Online (Sandbox Code Playgroud)
为了strFileName成为 unicode 字符串,您可以从单元格值获取它或以特殊方式定义它,因为 Excel 的 VBE 不会以 Unicode 保存字符串常量。VBE 支持已保存在字符串变量中的 Unicode 字符串。您必须查找此内容以获取更多详细信息。
希望这对某人有帮助^_^