WAY 1: Simple Way
Code:
Private Sub Command1_Click()
If Dir("C:\abc.txt") <> "" Then
MsgBox "File exists"
Else
MsgBox "File does not exist"
'~~> Code here to create the text file
Dim i As Long
Open "C:\abc.txt" For Output As #1
For i = 0 To 5
Print #1, i
Next i
Close #1
End If
'~~> If the file has special attributes (eg: is Hidden)
'~~> you need to specify as below
'If Dir("C:\abc.txt", vbHidden) <> "" Then
'MsgBox "File exists"
'End If
End Sub
WAY TWO: The API way
Code:
Option Explicit
Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, _
lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
Private Const OF_EXIST As Long = &H4000
Private Const OFS_MAXPATHNAME As Long = 128
Private Const HFILE_ERROR As Long = -1
Private Type OFSTRUCT
cBytes As Byte
fFixedDisk As Byte
nErrCode As Integer
Reserved1 As Integer
Reserved2 As Integer
szPathName(OFS_MAXPATHNAME) As Byte
End Type
Private Sub Command1_Click()
If FileExists("C:\abc.txt") = False Then
'~~> Your code to create the text File
Dim i As Long
Open "C:\abc.txt" For Output As #1
For i = 0 To 5
Print #1, i
Next i
Close #1
End If
End Sub
Private Function FileExists(ByVal Fname As String) As Boolean
Dim Ret As Long, Ofstr As OFSTRUCT
Ret = OpenFile(Fname, Ofstr, OF_EXIST)
If Ret <> HFILE_ERROR Then
FileExists = True
Else
FileExists = False
End If
End Function