2017-05-24 339 views
0

編輯:經過大量的幫助,沒有一個線索是怎麼回事,它的工作用開放的不同方法(see @JohnMuggin's help below) - 所以我取消註釋我原來的代碼並突然生效。VBA Workbook.Open(文件)返回Nothing

我只發現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)wbNothing。直到我在代碼中向下調用wb時,這不會產生任何錯誤。

較早的行Set wsL = ThisWorkbook.Worksheets(3)也將wsL設置爲Nothing

我使用調試器檢查了每一行和值,並確定myFile是正確的路徑,文件名和擴展名。

+0

工作簿是否打開? –

+0

@TimWilliams不,它不。 – MTJ

+0

什麼叫'CommandButton2_Click' - 它只是一個UserForm上的按鈕? (我必須問 - 我看到有人從UDF調用這樣的代碼。) – YowE3K

回答

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 
+0

您確定您的文件被命名爲「file.xlsx」 –

+1

,我在Workbooks.Open文件名:=「字符串」和「設置wb = ActiveWorkbook」中添加了它,它工作正常。於是我又替換了'string'並測試了'Workbooks.Open Filename:= myFile',並且工作正常。困惑,我刪除了這些行,並測試了原始的'設置wb = Workbooks.Open(myFile)',它突然工作。我不知道給出了什麼,但現在這些線條工作得很好。 – MTJ

+0

我們會把它填滿滿月...... –