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!
As discussed in comments, cannot select
Sheetsin VBA that are not active (orRangeobjects on them).For example the following code
will cause the error you are receiving.
In your case, it seems you are attempting to
Selecta sheet which is not active – yourmainWSobject is presumably not theActiveSheetat 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:Note that you can refer to the activated worksheet with the command
ActiveSheetto 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 Explicitas you can often run into all sorts of issues without havingOption Explicitat the top of your VBA code.