Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
im giving the for loop for two options as to what will happen if the file is not selected.
when i am not giving the for loop for then its working but then if i do not select a file it will show error

What I have tried:

Sub importedrfile()
Worksheets("sheet2").Activate
Dim scan As Integer
Dim myfilepath As String
myfilepath = Application.GetOpenFilename()
If myfilepath = True Then
Open myfilepath For Input As #1
x = 0
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, vbTab)
For scan = 0 To UBound(lineitems) - 1
        lineitems(scan) = Replace(lineitems(scan), Chr(34), "")
Next
ActiveCell.Offset(x, 0).Value = lineitems(0)
ActiveCell.Offset(x, 1).Value = lineitems(1)
ActiveCell.Offset(x, 2).Value = lineitems(2)
ActiveCell.Offset(x, 3).Value = lineitems(3)
ActiveCell.Offset(x, 4).Value = lineitems(4)
ActiveCell.Offset(x, 5).Value = lineitems(5)
ActiveCell.Offset(x, 6).Value = lineitems(6)
ActiveCell.Offset(x, 7).Value = lineitems(7)
ActiveCell.Offset(x, 8).Value = lineitems(8)
ActiveCell.Offset(x, 9).Value = lineitems(9)
ActiveCell.Offset(x, 10).Value = lineitems(10)
ActiveCell.Offset(x, 11).Value = lineitems(11)
ActiveCell.Offset(x, 12).Value = lineitems(12)

x = x + 1
Loop

Close #1
ElseIf myfilepath = False Then
MsgBox ("no file selected")
End If
End Sub
Posted
Updated 18-Sep-16 20:20pm
v2
Comments
Member 12737742 19-Sep-16 2:14am    
no i want to give the option of opening the browser and also a msgbox will be shown when no file is selected
Maciej Los 19-Sep-16 2:21am    
See my answer.
Member 12737742 19-Sep-16 6:40am    
thank you sir
Maciej Los 19-Sep-16 6:53am    
The best "Thank you" is when inquirer accepts solution ;)
Use green button.

1 solution

Application.GetOpenFilename Method (Excel)[^] displays the standard Open dialog box and gets a file name from the user without actually opening any files. When user cancel operation, this method returns False. So, below code is wrong!
VB
Dim myfilepath As String
myfilepath = Application.GetOpenFilename()
If myfilepath = True Then
Open myfilepath For Input As #1


As MSDN documentation states, you have to check if returned value is not equal to False.

VB
fileToOpen = Application _ 
 .GetOpenFilename("Text Files (*.txt), *.txt") 
If fileToOpen <> False Then 
 MsgBox "Open " & fileToOpen 
End If


As to your code, i'd modify it this way:
VB
Dim myfilepath As String
myfilepath = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If myfilepath = CStr(False) Then Exit Sub


For further information, please see: Programmatically Selecting Files in Excel for Windows and Excel for the Mac[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900