Vba Excel 2016宏找不到文件:运行时错误1004

Vba Excel 2016宏找不到文件:运行时错误1004,vba,excel,Vba,Excel,我试图在Excel 2016中使用VBA打开其他Excel文件时遇到问题。文件是否在同一目录中并不重要。我认为这与Excel 2016中阻止搜索的默认设置有关?宏在Excel 2010中起作用 Private Sub CommmandButton_Click() Dim source As String Dim temp As Workbook source = InputBox("Enter source") Set temp = Workbooks.Open(source) end s

我试图在Excel 2016中使用VBA打开其他Excel文件时遇到问题。文件是否在同一目录中并不重要。我认为这与Excel 2016中阻止搜索的默认设置有关?宏在Excel 2010中起作用

Private Sub CommmandButton_Click()
Dim source As String
Dim temp As Workbook

source = InputBox("Enter source")

Set temp = Workbooks.Open(source)

end sub

您允许用户做的不仅仅是点击。这是自找麻烦。相反:

Private Sub CommmandButton_Click()
Dim source As String
Dim temp As Workbook

source = Application.GetOpenFilename()

Set temp = Workbooks.Open(source)

end sub
此代码可以进一步增强为:

1.预先选择初始路径
2.设置文件类型
3.给予指导

4.优雅地处理取消

这里是一个使用
文件对话框
对象的示例解决方案

Private Sub CommmandButton_Click()
    Dim fDialog As FileDialog, _
        wb      As Excel.Workbook
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    With fDialog
        .AllowMultiSelect = False
        .Title = "Select a file"
        .InitialFileName = "C:\"
        .Filters.Clear
        ' Prevent Error by specifying that the user must use an excel file
        .Filters.Add "Excel files", "*.xlsx,*.xls,*.xlsm"
    End With
    If fDialog.Show = -1 Then
       Set wb = Excel.Workbooks.Open(fDialog.SelectedItems(1))
    Else 
        End  ' Cleanly exit the Macro if the user cancels
    End If

End Sub

你确定你在输入框中输入的路径正确吗?它的格式应该是
C:\Folder\File.xlsx
也许你可以用一个而不是一个输入框?你真的在输入框中输入了完整的文件路径吗?为什么不使用类似于
Application.Getopenfilename
的东西呢?@VincentG是对的。不要让用户键入此内容。请看:谢谢大家的意见!非常感谢。这太完美了!