3 回答

TA貢獻1865條經驗 獲得超7個贊
像這樣的東西
最好使用工作簿變量來提供對打開的工作簿的進一步控制(如果需要)
已更新以測試文件名是實際的工作簿-這也使初始檢查變得多余,除了向用戶發送消息以外,文本框為空
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

TA貢獻1900條經驗 獲得超5個贊
我使用此功能檢查文件是否存在:
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

TA貢獻1799條經驗 獲得超9個贊
為了檢查是否存在,還可以使用(適用于文件和文件夾):
Not Dir(DirFile, vbDirectory) = vbNullString
結果是True文件或目錄是否存在。
例:
If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
MsgBox "exists"
Else
MsgBox "does not exist"
End If
- 3 回答
- 0 關注
- 625 瀏覽
相關問題推薦
添加回答
舉報