We help IT Professionals succeed at work.

Excel - VBA "Object doesn't support this property or method"

1,865 Views
Last Modified: 2017-03-29
I have an Excel workbook that executes a macro when being opened. During the process the macro creates a number of worksheets and then saves itself and closes.

Prior to saving I would like a certain worksheet to be selected. So if I ever was to open the workbook  I don't have to change worksheets.

This code usually works well...
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    ThisWorkbook.Worksheets("Create Report").Select
    ThisWorkbook.Worksheets("Create Report").Range("A1").Select
End Sub

Sometimes there are 2 or more workbooks open at once.
If the workbook is not selected when the macro runs this error is generated...
"Object doesn't support this property or method" for this line ThisWorkbook.Worksheets("Create Report").Select

How can I work around this? I want the macro to set "Create Report" as the active/selected sheet in the workbook and then close it without the workbook itself having to be the focused/active window.
Comment
Watch Question

ShumsManaging Director/Excel VBA Developer
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
Hi,

Try below:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
ThisWorkbook.Worksheets("Create Report").Activate
    ThisWorkbook.Worksheets("Create Report").Range("A1").Select
End Sub

Open in new window

Antonio KingIT Manager

Author

Commented:
Hi Shums
That also generates the same RunTime error.
ShumsManaging Director/Excel VBA Developer
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
Hi Alan,

Sample data would be helpful with your code.
Microsoft Excel Expert
CERTIFIED EXPERT
Top Expert 2014
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Antonio KingIT Manager

Author

Commented:
Thanks for this!
This works great.
Professor JMicrosoft Excel Expert
CERTIFIED EXPERT
Top Expert 2014

Commented:
you are welcome. i am glad i was able to help.
Roy CoxGroup Finance Manager
CERTIFIED EXPERT

Commented:
In such cases I would use an alternative

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.Goto ThisWorkbook.Worksheets("Create Report").Range("A1")
End Sub

Open in new window


Adding  scroll:=True will force the sheet to scroll to the range

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.Goto ThisWorkbook.Worksheets("Create Report").Range("A1"), scroll:=True
End Sub

Open in new window