Reputation: 97
I want to prompt the user to select the raw data file, and abort if they click "Cancel" on the FileDialog box.
But i am getting the debug option and the error message "runtime error 424 object required" on the line :
FileDialog.SourceDataFile = fdgOpen.SelectedItems(1)
As i am quite new to the whole open-a-file-like-this method, any help will be appreciated!
Sub Open file
Dim fldr As FileDialog
Dim Answer As Integer
Dim fdgOpen As FileDialog
sPath = Environ("USERPROFILE") & "\Skrivebord\"
Set fdgOpen = Application.FileDialog(msoFileDialogOpen)
Answer = MsgBox("Continue? ", vbYesNo + vbQuestion, "Update")
If Answer = vbNo Then GoTo Nej Else
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
fdgOpen.Title = "FileDialogTitle"
fdgOpen.InitialFileName = "Select raw data"
fdgOpen.Show
If fdgOpen.SelectedItems.Count <= 0 Then GoTo Nej Else
FileDialog.SourceDataFile = fdgOpen.SelectedItems(1)
Nej: MsgBox ("You cancelled")
End sub
Upvotes: 1
Views: 1800
Reputation: 149287
You are getting the Object Required
error because your code doesn't understand what FileDialog
is in FileDialog.SourceDataFile = fdgOpen.SelectedItems(1)
Here is a much simpler version which uses the native Excel's Application.GetOpenFilename
Is this what you are trying?
Sub Openfile()
Dim Ret, Ans
Ans = MsgBox("Continue? ", vbYesNo + vbQuestion, "Update")
If Ans = vbNo Then
MsgBox "You cancelled"
Else
Ret = Application.GetOpenFilename("Raw Data Files (*.*), *.*", , "Select Raw Data")
If Ret = False Then
MsgBox "You cancelled"
Else
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Workbooks.Open Ret
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End If
End If
End Sub
EDIT
This is how you will o it using the FileDialog
Sub Openfile()
Dim dlgOpen As FileDialog
Dim Ans
Dim sPath As String
Ans = MsgBox("Continue? ", vbYesNo + vbQuestion, "Update")
sPath = Environ("USERPROFILE") & "\Skrivebord\"
If Ans = vbNo Then
MsgBox "You cancelled"
Else
Set dlgOpen = Application.FileDialog( _
FileDialogType:=msoFileDialogOpen)
With dlgOpen
.Title = "Select Raw Data"
'~~> Add the folder path and file name
.InitialFileName = sPath & "Myfile.xlsx"
.Show
If .SelectedItems.Count > 0 Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Workbooks.Open .SelectedItems(1)
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Else
MsgBox "You cancelled"
End If
End With
End If
End Sub
Upvotes: 1