1

I am currently writing a Programm using VBA, which opens particular excel files from the folder C:Reports. I Need to be able to open the file dynamically from user input in this folder such as;

1)User gets an Dialog box and sees the first question "What is the Name of the file" where he/she has to type the Filename without seeing the folder of the file. The file Name he typed has to be in C:Reports, else it should print "File not Found"

2)After entering file Name, he gets another question about the ID number, which is a value in a column in the desired file to open includes. If the file Name matches with the ID inside of the file then the file should be opened, else it should print "file Name and ID does not match"

Does anyone have Solution for this ?

2
  • Awesome! harun24hr thx a lot! Commented Feb 15, 2016 at 13:00
  • You should accept my answer as it works for you. Tick as green my answer. Commented Feb 17, 2016 at 3:58

1 Answer 1

1

Check this sub. This should work for you

Sub OpenFileIfDataExist()
On Error GoTo HarunErrHandler
Dim strWorkBook As Excel.Workbook
Dim SearRange As Range
Dim FSO As Object
Dim strFileName, strFilePath As String
Dim strID As String
Dim lnCheckID As Long

    strFileName = InputBox("Enter your file name.", "File Name")
    strFilePath = "C:\Reports\" & strFileName & ".xlsx"
    Set FSO = CreateObject("scripting.filesystemobject")


    If FSO.FileExists(strFilePath) = True Then
        Set strWorkBook = GetObject(strFilePath)
        Set SearRange = strWorkBook.Sheets(1).Range("A1:A1000")

           strID = InputBox("Enter ID.", "ID Input")
           lnCheckID = Application.WorksheetFunction.Match(strID, SearRange, 0)

             If lnCheckID > 0 Then
                Workbooks.Open (strFilePath)
             End If

    Else
        MsgBox "File Name does not match"
    End If

Exit Sub
HarunErrHandler:
MsgBox "File Name and ID does not match.", vbInformation, "Nothing Found"
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

You have to edit little for your desired column and range. I used Sheet1 as sheet and Range("A1:A1000") as search range.
Remember another thing, I use file extension .xlsx.If your file extension is different (xls, xlsm etx) then correct it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.