Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Select of Object '_Worksheet' failed - why?

Set mainWB = Workbooks("Copy Paste.xlsb")
Set mainWS = mainWB.Sheets("Sheet1")
Set testWS = mainWB.Sheets("Sheet3")

mainWS.Select

I keep getting an error on the last line in Excel VBA:

"Method Select of Object '_Worksheet' failed"

Any idea why or how to fix this? Thank you!

like image 399
Sam Avatar asked Oct 02 '12 20:10

Sam


People also ask

How do I fix Runtime Error 1004 Method range of object UNK worksheet failed?

The best way to deal with this error is to activate the sheet first and then write a line of code that selects a cell or the range from that sheet.

What is difference between select and activate in Excel VBA?

The short answer is that Select and Activate can perform the same action, but the differences are: Select can be used to select multiple objects (sheets, ranges, shapes, etc.) at the same time. Activate can be used to active one object within the selection.


1 Answers

As discussed in comments, cannot select Sheets in VBA that are not active (or Range objects on them).

For example the following code

Sheets(1).Activate
Sheets(2).Range("A1").Select

will cause the error you are receiving.

In your case, it seems you are attempting to Select a sheet which is not active - your mainWS object is presumably not the ActiveSheet at the point you are calling this code. An easy way to test if this is happening is if you add the following to the end of your code:

if (ActiveSheet.Name <> mainWS.Name) then
    msgbox ("Going to crash after clicking ok!")
end if
mainWS.Select

Note that you can refer to the activated worksheet with the command ActiveSheet to either get properties or whatever other operations you are interested in doing.

This error can also happen if you have loop working thru all of the worksheets in the workbook and there are hidden sheets. Lookout for that.


Last, and unrelated to your specific error message, I assume you are declaring those variables somewhere and simply did not copy them here - if not I would consider using Option Explicit as you can often run into all sorts of issues without having Option Explicit at the top of your VBA code.

like image 147
enderland Avatar answered Oct 04 '22 01:10

enderland