I have an external program which starts up excel from a batch with a specific parameter(CREO) and then moves,reads textfiles and dumps some of this data into an existing excel file. Everything is working fine, except if another user has the excel sheet which it should dump data into open. Then my script prompt the user with" Another user has the file open, rerun the batch file manually after the XXX file has been closed"
However this other user might actually be the same user, because the batch script starts a new instance of excel. Is there a method to reference a workbook in another instance of excel run by the same user?
here is my getworkbook method:
Public Function GetWorkbook(ByVal sFullName As String) As Workbook
Dim sFile As String
Dim wbReturn As Workbook
sFile = Dir(sFullName)
On Error Resume Next
Set wbReturn = Workbooks(sFile)
If wbReturn Is Nothing Then
If isWorkbookOpen(sFullName) Then
MsgBox "Workbook open by another user, sorry mate"
Set wbReturn = Nothing
Else
Set wbReturn = Workbooks.Open(sFullName)
End If
End If
On Error GoTo 0
Set GetWorkbook = wbReturn
End Function
and the function that check if the file is in use by another instance:
Function isWorkbookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: isWorkbookOpen = False
Case 70: isWorkbookOpen = True
Case Else: Error ErrNo
End Select
End Function
Here is my batch script code that fires up the second instance which then either should do everything in that instance or switch to the other instance if that instance has the workbook open.
echo "Launch excel"
Set ExcelArgs=CREO
"C:\Program Files (x86)\Microsoft Office\OFFICE16\Excel.exe" /r /e "%APPDATA%\Microsoft\Excel\XLSTART\PERSONAL.XLSB"
exit 0
GetObjectand pass the file path. It will grab a reference to the existing instance, if any, or open it if not.GetObjectmay work, but it is not reliable. This method will get an instance of Excel, but, if that is not the right one, it will not allow you to then try to get another instance.Excel.Applicationclass, you will get the first instance loaded (since that's what will be registered in the ROT), but passing a file path will either attach to the file if it's open, or open it.GetObjectmethod to capture a specific Excel instance if you know the exact path of the desired workbook. 'Set obj = GetObject(wbPath) Set xl = obj.Application'. It is only necessary to use an alternative approach if the file path may change.