Home » excel » excel – VBA function to check if a workbook exists

excel – VBA function to check if a workbook exists

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have two workbooks 1: Source.xlsx and 2. Destination.xlsx. If the #2 exists in the same location as that of #1, then return the workbook to my main function, else create a new workbook and return it.
I have the following code:

Function CheckForExistingWorkbooks() As Workbook
Dim wb1 As Workbook
Dim FilePath As String
Dim TestStr As String

FilePath = ThisWorkbook.Path & "\Student Information.xlsx"

TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
    Set wb1 = Workbooks.Add
Else
    Set wb1 = Workbooks.Open(FilePath)
End If

CheckForExistingWorkbooks = wb1
End Function 

On debugging, the function returns “Nothing”. How do I get this to work?

How to&Answers:

Try this – without needing error detection:

Function CheckForExistingWorkbooks() As Workbook
    Dim wb1 as Workbook
    Dim TestStr As String, FilePath As String
    FilePath = ThisWorkbook.Path & "\Student Information.xlsx"
    If Len(Dir(FilePath)) = 0 Then
        Set wb1 = Workbooks.Add
    Else
        Set wb1 = Workbooks.Open(FilePath)
    End If
    Set CheckForExistingWorkbooks = wb1
End Function