VBA Workbook.Open(File)返回Nothing

时间:2017-05-24 22:11:28

标签: excel vba excel-vba

编辑: 经过大量的帮助并且不知道发生了什么,它使用了不同的打开方法(see @JohnMuggin's help below) - 所以我没有发表评论我原来的代码突然就行了。

我只发现了另一个Workbook.Open("file")没有返回(Link to Q)的实例。但是,他们的问题是因为在用户定义的函数中调用Workbook.Open("file")(根据我的理解)。在这里,我在Sub中调用它,但我遇到了同样的问题,无法找到解决方案。我正在使用Excel 2013。

Private Sub CommandButton2_Click()

'Set variables
Dim wb As Workbook 'Workbook to open
Dim wbR As Worksheet 'This is the raw data on the new workbook
Dim wsL As Worksheet 'Worksheet in current file
Dim myFile As String 'File to open
Dim FilePicker As FileDialog

'Set light chain hit worksheet
Set wsL = ThisWorkbook.Worksheets(3)

'Optimizes Speed
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
Set FilePicker = Application.FileDialog(msoFileDialogFilePicker)

'Opens folder-picking window
With FilePicker
    .Title = "Select a file."
    .AllowMultiSelect = False
    If .Show = True Then
        myFile = .SelectedItems(1)
    Else: GoTo NextCode
    End If
End With

'If folder is not selected
NextCode:
    myFile = myFile
    If myFile = "" Then GoTo ResetSettings

'Set variable equal to opened workbook
Set wb = Workbooks.Open(myFile)

宏继续,但最后一行Set wb = Workbooks.Open(myFile)wb设置为Nothing。在我在代码中调用wb之前,这不会产生任何错误。

较早的行Set wsL = ThisWorkbook.Worksheets(3)也将wsL设为Nothing

我已使用调试器检查了每一行和每个值,并确定myFile是正确的路径,文件名和扩展名。

1 个答案:

答案 0 :(得分:1)

在最后一次尝试这个小子。如果它没有打开您的工作簿,则路径或文件名存在问题

Sub opendfghj()

Dim wb As Workbook

Workbooks.Open Filename:="C:\Users\User\Desktop\Templates and Example data\Repeat Tests\file.xlsx"

Set wb = ActiveWorkbook

wb.Worksheets("Sheet1").Range("A1") = "It Works"
End Sub