问题
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