If file not open then open a file from same folder

misiek5510

New Member
Joined
May 25, 2021
Messages
38
Office Version
  1. 2016
Platform
  1. Windows
  2. Mobile
What I'm trying to do is to detect if excel file is already open and if it is then to open specific tab and if its not open to open it from same folder and then open specific tab.

My current code opens the file I need and selects the sheet I wanted however if the file is already open then it asks if I want to reopen it.

Sub test()
Workbooks.Open (ThisWorkbook.Path & "\test.xlsm")
Sheets("testing").Select
End Sub
 

Excel Facts

Move date out one month or year
Use =EDATE(A2,1) for one month later. Use EDATE(A2,12) for one year later.
Upvote 0
Do not forget to post your code attempt just using the VBA icon …​
 
Upvote 0
I managed to fix it. For everyone with the same issue in future here is the code:


Function IsWorkBookOpen(Name As String) As Boolean
Dim xWb As Workbook
On Error Resume Next
Set xWb = Application.Workbooks.Item(Name)
IsWorkBookOpen = (Not xWb Is Nothing)
End Function

Sub Sample()
Dim xRet As Boolean
xRet = IsWorkBookOpen("TEST.XLSM")
If xRet Then
Workbooks("TEST.xlsm").Activate
Sheets("SHEET1").Select
Else
Workbooks.Open (ThisWorkbook.Path & "\TEST.xlsm")
Sheets("SHEET1").Select
End If
End Sub
 
Upvote 0
Solution
Do not forget at least to clear the useless workbook variable …​
 
Last edited:
Upvote 0
Set ObjectVariable = Nothing before exiting the procedure, the reason why IsObject function is the best way …​
 
Upvote 0

Forum statistics

Threads
1,215,219
Messages
6,123,690
Members
449,117
Latest member
Aaagu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top