3

I am importing a worksheet from another workbook to my current workbook. After I complete importing the worksheet, I want to close that other workbook. The code I am using gives the error Run-time error 9': Subscript out of range.

Sub ImportWorksheet(MyPath As String, wbName As String)

ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=MyPath
Sheets(1).Copy After:=Workbooks(ControlFile).Sheets(1)
ActiveSheet.Name = wbName
Workbooks(MyPath).Close SaveChanges:=False
Windows(ControlFile).Activate

End Sub

I also tried using

Windows(MyPath).Activate
ActiveWorkbook.Close SaveChanges:=False

But I get the same error.

1
  • 1
    I'm guessing MyPath is a file path, which works fine when you're opening a workbook by it's Filename, but when using Workbooks().Close you need to list the workbook's name, not it's path. Try using Workbooks(Dir(MyPath)).Close SaveChanges:=False. Commented Jul 24, 2018 at 20:50

3 Answers 3

2

Since Open method of Workbooks object returns a Workbook object you can reference the opened workbook:

Sub ImportWorksheet(MyPath As String, wbName As String)
    ControlFile = ActiveWorkbook.Name
    With Workbooks.Open(Filename:=MyPath)
        .Sheets(1).Copy After:=Workbooks(ControlFile).Sheets(1)
        .Sheets(2).Name = wbName
        .Close SaveChanges:=False 
    End With 
End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

I like to assign variable, it removes any confusion.

Sub ImportWorksheet(MyPath As String, wbName As String)


Dim Owb As Workbook
Dim Nwb As Workbook

Set Owb = ThisWorkbook
Set Nwb = Workbooks.Open(Filename:=MyPath)

Nwb.Sheets(1).Copy after:=Owb.Sheets(1)
Owb.Sheets(2).Name = wbName

Nwb.Close False
Owb.Activate

End Sub

Comments

-1
Workbooks(strTargetFileName).Close SaveChanges:=False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.