VBA Run-time error '9': Subscript out of range; trying to activate another workbook

允我心安 提交于 2020-01-11 06:18:29

问题


I'm trying to create a VBA in Excel 2010 that takes info from another spreadsheet that I'm not allowed to alter and bring it over to the spreadsheet with my macro built in. Here's my code:

Sub BringUpWorkbook()
    Workbooks("RITE 1624.xls").Activate
End Sub

I have several VBA books, have visited dozens of sites on the Internet, including those here at stackoverflow.com, and cannot find a reason why I'm receiving the run-time error. The workbook is already open, I've tried adding everything trailing the title, I've tried removing the .xls, I've even did all of the above with in a variable. Any ideas?


回答1:


Make sure the extension is correct. If it's a excel-2010 file like you indicate, you may need to update your code to reflect the extension of your "RITE 1624" file (e.g. .xlsx for a 2010 Excel workbook, .xlsm for a 2010 Excel macro-enabled workbook, or whatever the extension is.

Sub BringUpWorkbook()
    Workbooks("RITE 1624.xlsx").Activate
End Sub

EDIT:

To make sure you have the right name of the workbook, you can print the name of each workbook in an immediate window.

Open up the VBA editor, and then press Ctrl+G to open the Immediate Window (or do View > Immediate window). Then run the following Macro:

Sub OpenWkbkNames()

For Each Workbook In Workbooks
    Debug.Print Workbook.Name
Next
End Sub

Note that this will give you the names of all the open workbooks in the same Excel instance as your macro. If your RITE 1624 file is in a separate Excel instance, then the instance that your macro is in will not be able to see that file (and it won't appear in the output of the OpenWkbkNames code above). The simplest way to resolve this is to open all of your necessary files from the Excel instance that contains your macro.

Sub BringUpWorkbook()

    Workbooks.Open("RITE 1624.xls").Activate
End Sub


来源:https://stackoverflow.com/questions/18193153/vba-run-time-error-9-subscript-out-of-range-trying-to-activate-another-workb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!