
Tips.Net > ExcelTips Home > Macros > Selecting a Specific Cell in a Macro
Summary: How you select a specific cell in a worksheet depends on many factors. This tip examines how you can select a specific cell in a specific worksheet of a specific workbook. Use the wrong approach, and you end up with an error; use the techniques here and you can enjoy success. (This tip works with Microsoft Excel 97, Excel 2000, Excel 2002, and Excel 2003.)
It is often necessary to select a particular cell in a macro. It is harder, however, to select that cell if it is in a different workbook. For instance, consider the following two lines of code:
Sub CellSelect1()
Workbooks("pwd.xls").Sheets("Sheet3").Select
ActiveSheet.Range("A18").Select
End Sub
You might think that this macro will select Sheet3!A18 in the pwd.xls workbook. It does, with some caveats. If you have more than one workbook open, this macro results in an error, if pwd.xls isn't the currently active workbook. This occurs even if pwd.xls is already open, but simply not selected.
The same behavior exists even when you condense the selection code down to a single line:
Sub CellSelect2()
Workbooks("pwd.xls").Sheets("Sheet3").Range("A18").Select
End Sub
You still get the error, except when pwd.xls is the currently selected worksheet. The solution is to entirely change how you perform the jump. Instead of using the Select method, use the Goto method and specify a target address for the method:
Sub CellSelect3()
Application.Goto _
Reference:=Workbooks("pwd.xls").Sheets("Sheet1").[A18]
End Sub
This code will work only if pwd.xls is already open, but it doesn't need to be the currently active workbook. If you want the target workbook to be scrolled so that the specified cell is in the upper-left corner of what you are viewing, then you can specify the Scroll attribute to be True, as shown here:
Sub CellSelect4()
Application.Goto _
Reference:=Workbooks("pwd.xls").Sheets("Sheet1").[A18] _
Scroll:=True
End Sub
Tip #2791 applies to Microsoft Excel versions: 97 2000 2002 2003
Got the Time? Understanding the ins and outs of working with times and dates can be confusing. Remove the confusion--ExcelTips: Times and Dates is an invaluable resource for learning how best to work with times and dates.
Check out ExcelTips: Times and Dates today!
PivotTables don't need to be scary or mysterious. Use this powerful tool to analyze your data in ways you didn't know were possible. (more information...)
Ask an Excel Question
Make a Comment
ExcelTips FAQ
ExcelTips Premium
Bugs and Pests Tips
ExcelTips
Family Tips
Health Tips
Home Tips
Organizing Tips
WordTips
Advertise on the
ExcelTips Site