Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

excel - VBA Workbook.Open(File) returns Nothing

EDIT: After lots of help and not having a clue what's going on, it worked using a different method of opening (see @JohnMuggin's help below)--so I un-commented my original code and suddenly it works.

I've only found one other instance of Workbook.Open("file") returning nothing (Link to Q). However, their problem was because of calling Workbook.Open("file") in a user-defined function (to my understanding). Here, I am calling it in a Sub, but am having the same issue and can't find a solution. I am using 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)

The macro continues, but the last line Set wb = Workbooks.Open(myFile) sets wb as Nothing. This does not produce any errors until I call wb farther down in the code.

An earlier line, Set wsL = ThisWorkbook.Worksheets(3), also sets wsL as Nothing.

I have checked each line and values using the debugger, and have determined myFile is the proper path, file name, and extension.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a copy of the workbook open (in a different folder) with the same name as the one your VBA is trying to open, it fails silently. The ActiveWorkbook solution appears to work - as you have at least one workbook open already - and that is active - but its not the one you think it is.

I imagine it it could be a common mistake - as while developing a VBA project you might have a copy of the target workbook open to check on column numbers etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...