Excel automation: connecting to Excel

J

Jack

Which one is better (safer) way to do:

1.
If moExcelApp.Workbooks.Count > 0 Then 'when any sheet is opened
Set moExcelWS = moExcelApp.ActiveWorkbook.ActiveSheet
End if

or

2.
If moExcelApp.Workbooks.Count > 0 Then 'when any sheet is opened
Set moExcelWS = moExcelApp.moExcelApp.Workbooks(1).Worksheets(1)
End if

Jack
 
T

Tim Williams

They appear to do different things...
The first gets a reference to the activesheet, the second (ignoring the
duplicate app reference) gets a reference to the first sheet of the first
workbook.

Can you provide some context around what you want to do?

Tim
 
J

Jack

Thank you.
I need to connect my app to any Excel spreadsheet, which currently is
opened.
In the case if there are several spreadsheets opened, it does not matter
which one will be used.
Jack
 
D

Dave Peterson

If there are open workbooks, but all are hidden (no active sheet), then won't
both have trouble.

set moexcelws = nothing
on error resume next
Set moExcelWS = moExcelApp.ActiveWorkbook.ActiveSheet
on error goto 0

if moexcelws is nothing then
'failed
else
'worked
end if
 
T

Tim Williams

Dave's post shows how.
Don't forget to check the typename of the sheet you get, in case it's a
chart and not a worksheet.

Tim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top