Link to home
Get AccessLog in
Avatar of Antonio King
Antonio King

asked on

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

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.
Avatar of Shums Faruk
Shums Faruk
Flag of India image

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

Avatar of Antonio King
Antonio King

ASKER

Hi Shums
That also generates the same RunTime error.
Hi Alan,

Sample data would be helpful with your code.
ASKER CERTIFIED SOLUTION
Avatar of Professor J
Professor J

Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Thanks for this!
This works great.
you are welcome. i am glad i was able to help.
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