Open a file with user Input in Excel VBA

旧时模样 提交于 2019-12-08 13:01:44

问题


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 ?


回答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


来源:https://stackoverflow.com/questions/35405278/open-a-file-with-user-input-in-excel-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!