Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

check if file exist in folder code not working

Status
Not open for further replies.

lemonhalls

Technical User
Jun 11, 2004
52
CA
I would really appreciate if someone could look over this sub and let me know what's wrong with particularly the for loop.
I am trying to check if a file exist already, if it does not save it as ver1, if it does exist, check if ver2 exist and save it as the next available version.

I'm running the code and it seem to say ver1 exist whether or not it exists already.
Would someone be kind enough to look over the for loop?

Many thanks,

S
___________

Sub saveReport()

'saves the report in the same directory as the merged files
'appends the system date at the end of the file name
'closes the template

Dim strPrevMonth As Date 'stores the previous month
Dim lastMonth As String
Dim i As Integer
Dim aField As Field
Dim fso As New FileSystemObject

' make current document an object
Set aDoc = ActiveDocument
Set aField = aDoc.Fields(1) 'aField = the compile button

'deletes the control button
If aField.Type = 87 Then aField.Delete

'Getting last month
strPrevMonth = DateSerial(Year(Date), Month(Date) - 1, 1)
lastMonth = Format(strPrevMonth, "MMMM")

'checks to see if a file exists in a folder
For i = 1 To 2
'a copy of the file exists in the folder
If fso.FileExists(newDir & "_DBReport" & lastMonth & i) = True Then
MsgBox (fso.FileExists(newDir & "_DBReport" & lastMonth & i) & " TRUE " & i)
Else
'a copy of the file does not exist in the folder
MsgBox ("A copy of " & "_DBReport" & lastMonth & i & " already exists. " _
& vbCrLf & "This version will be saved as _DBReport" & lastMonth & i)

aDoc.SaveAs FileName:=newDir & "_DBReport" & lastMonth & i + 1
End If
Next i


 
Where your MsgBox says 'already exists' it should say 'does not exist' maybe this is causing the confusion.

Code:
For i = 1 To 2
    'a copy of the file exists in the folder
    If fso.FileExists(newDir & "_DBReport" & lastMonth & i) = True Then
        MsgBox (fso.FileExists(newDir & "_DBReport" & lastMonth & i) & " TRUE " & i)
    Else
        'a copy of the file does not exist in the folder
        MsgBox ("A copy of " & "_DBReport" & lastMonth & i & " [red]does not exist[/red].  " _
        & vbCrLf & "This version will be saved as _DBReport" & lastMonth & i)
        
        aDoc.SaveAs FileName:=newDir & "_DBReport" & lastMonth & i + 1
    End If
Next i
 
thanks!! i'll try to debug it more, but that definitely helps!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top