TotallyConfused
Board Regular
- Joined
- May 4, 2017
- Messages
- 247
- Office Version
- 365
- Platform
- Windows
VBA Code:
' I need some way to determine whether or not a given file exists. The past couple of days have been spent searching the internet and
' trying different pieces of code I've found. None of them work for me.The second workbook, "MasterDataFile.xlsm" was created by me
' and works okay. The problem is that this program will be used by another person, so I'd like to have ThisWorkbook create the file the
' first time the user runs this program rather than have them create this data file.This should avoid the possibility of them making a
' spelling error or placing the data file in the wrong place, etc. This file will only be created once, then used over and over, so that's why
' I need that 'IF' statement.
'
Sub DoesFileExist()
Dim fPath As String ' Path where data and programs are at
Dim fName As String ' File name of Master data file
fName = "MasterDataFile.xlsm" ' Assign name of MasterDataFile, which stores ALL of the data, to a variable
fPath = Application.ActiveWorkbook.Path & "\" ' Determine path for the MasterDatafile.xlsm based on Activeworkbook path
fName = fPath & fName ' Determine full path and file name of MasterDataFile.xlsm
' Workbooks.Open fName
'******* Above code using Workbooks.Open fName works because MasterDataFile.xlsm DOES exist, so the file does open *******
' The following code was posted to MrExcel by someone named "DK" on April 12, 2004. The link to this is:
' https://www.mrexcel.com/board/threads/how-to-check-if-file-exists.61179/page-2#posts
' The only change I've made is to comment out the original line of 'If oFSO.fileexists...." and insert what I hoped would work for me.
' I'm unable to code in the exact path because this program will be used by another person, so I'm using a variable instead.
' I've tried different versions, including putting everything inside parenthesis, using fName by itself, etc. I either get an immediate
' syntax error message or MsgBox says it doesn't exist.
'Sub LateBinding()
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FilesystemObject")
If oFSO.fileexists(fName) = True Then ' If oFSO.fileexists(fPath) & "MasterDataFile.xlsm" = True Then
' If oFSO.fileexists("H:\temp\myfile.xls") = True Then
MsgBox "It exists!"
Else
MsgBox "Sorry mate, it doesn't exist."
End If
' End Sub
End Sub
' I have no emotional attachment to the above code, in fact, I have no idea what the line of 'Set oFSO...' does. I found this macro
' and hoped I could adapt it to my use. If you can tell me what I'm doing wrong here or you have some other code that will tell me
' whether or not a file exists, I'd sure appreciate it. I'd love to receive any help or suggestions you may be able to offer.
' THANK YOU in advance.
TotallyConfused
Last edited: