karan arora
karan arora

Reputation: 41

VBA not finding the excel file even when file is present in the folder

I am opening the excel file in VBA using

Set Workbook = Application.Workbooks.Open(File)

Where

File = "C:\GSTR Automation\GSTR2\February\1000\ReverseCharge\Outputs\ReverseChargeZonic_1000.xlsx"

I am getting the vba error that it could'nt find the file.

Upvotes: 1

Views: 109

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149277

But file is present there , I have verified the path manually – karan arora 33 mins ago

I have copied the file location and name from the file still getting the same error – karan arora 30 mins ago

This is not an answer but may help you identify where could be the problem in such a scenario.

Logic:

This code (not fully tested) will take a path and folder by folder will check if it exists. I created the same structure in my C: so that you can see how it works

enter image description here

Code:

Option Explicit

Sub Sample()
    Dim sFile As String
    Dim Ar As Variant
    Dim i As Long
    Dim DoesFileExist As Boolean
    
    sFile = "C:\GSTR Automation\GSTR2\February\1000\ReverseCharge\Outputs\ReverseChargeZonic_1000.xlsx"
    
    Ar = Split(sFile, "\")
    
    If UBound(Ar) = 1 Then
        MsgBox "File Exists: " & FileFolderExists(sFile)
    Else
        sFile = Ar(0)
        
        For i = 1 To UBound(Ar)
            sFile = sFile & "\" & Ar(i)
            
            DoesFileExist = FileFolderExists(sFile)
            
            If DoesFileExist = False Then
                MsgBox sFile & " not found"
                Exit Sub
            Else
                MsgBox sFile & " found"
            End If
        Next i
    End If
End Sub

'~~> Function to check if file/folder exists
Private Function FileFolderExists(strFullPath As String) As Boolean
    On Error GoTo Whoa
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True
Whoa:
    On Error GoTo 0
End Function

In Action:

enter image description here

Now I changed February to January in the above path

enter image description here

Now see how the above code responds

enter image description here

Upvotes: 2

Related Questions