VBA Excel 2010 msoFileDialogOpen Path.Open运行时错误“424”:需要的对象

我有一个简单的函数,让用户使用Excel 2010的VBA的msoFileDialogOpen属性select一个文件来select一个文件。 当我运行它时,我得到了错误:

运行时错误“424”:

所需对象

这是违规的路线:

Path.Open 

这是整个function:

 Public Sub Function4_FileExplorer() Dim file As Variant ' Start File Explorer to select file containing data (simple GUI, much easier than coding vFileName) With Application.FileDialog(msoFileDialogOpen) .AllowMultiSelect = False If .Show Then file = .SelectedItems(1) Path = file End If Path.Open End With MsgBox file Exit Sub ErrorHandler: MsgBox "Error detected" & vbNewLine & "Error" & Err.Number & _ Err.Description, vbCritical, "Error Handler: Error " & Err.Number End Sub 

我应该如何解决这个运行时错误? 我谢谢你!

path是一个String所以没有.Open方法(即使对话被解散,你.Open调用;即当.Show返回false

假设你想打开选定的工作簿(你应该添加一个xls / x / mfilter)

 Dim file As String ' Start File Explorer to select file containing data (simple GUI, much easier than coding vFileName) With Application.FileDialog(msoFileDialogOpen) .AllowMultiSelect = False If .Show Then file = .SelectedItems(1) Workbooks.Open file End If End With 

原因是您将string值分配给variablesPath ,之后您正尝试调用方法Open此string:

 Path.Open 

string是一个原始值,它没有任何方法。 你可以使用它作为函数的参数,但是你不能调用它自己的方法,因为它们没有。