运行时错误 424:FileDialog.SourceDataFile & fdgOpen.SelectedItems(1) 需要对象

Runtime error 424: object required with FileDialog.SourceDataFile & fdgOpen.SelectedItems(1)

我想提示用户 select 原始数据文件,如果他们在文件对话框上单击 "Cancel" 则中止。

但我在行中收到调试选项和错误消息 "runtime error 424 object required":

FileDialog.SourceDataFile = fdgOpen.SelectedItems(1)

由于我对整个类似打开文件的方法还很陌生,如有任何帮助,我们将不胜感激!

    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

您收到 Object Required 错误是因为您的代码不理解 FileDialog 中的内容 FileDialog.SourceDataFile = fdgOpen.SelectedItems(1)

这是一个更简单的版本,它使用原生 Excel 的 Application.GetOpenFilename

这是你正在尝试的吗?

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

编辑

这就是您将如何使用 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