Excel 2016宏无法找到文件:运行时错误1004

时间:2018-06-07 14:13:30

标签: excel vba excel-vba

尝试在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

2 个答案:

答案 0 :(得分:3)

以下是使用FileDialog对象

的示例解决方案
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

答案 1 :(得分:1)

您允许用户执行的操作不仅仅是指向和单击。这是在惹麻烦。代替:

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.优雅处理取消