Test if an Excel file is open

Test if an Excel file is open

Anonymous
Not applicable
839 Views
2 Replies
Message 1 of 3

Test if an Excel file is open

Anonymous
Not applicable
I am trying to write a function that checks if an Excel workbook is open (read only or not), and if it’s open assign a variable to it.
I have found many examples of how to test if an Excel workbook is open from excel VBA, but can’t get it to work in AutoCad VBA. Any help in getting this code to work in Autocad would be appreciated.

This is the Testing function I have so far:

Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False

Dim Wbk As Workbook

'On Error GoTo WorkBookNotOpen

If Len(Excel.Application.Workbooks(WorkBookName).Name) > 0 Then
MsgBox "WorkbookOpen = True", , "Testing MsgBox"

WorkbookOpen = True

Exit Function
End If

MsgBox "WorkbookOpen = False", , "Testing MsgBox"

WorkBookNotOpen:
End Function

Thanks,
Kai
0 Likes
840 Views
2 Replies
Replies (2)
Message 2 of 3

Anonymous
Not applicable
look into GetObject and CreateObject
0 Likes
Message 3 of 3

arcticad
Advisor
Advisor
This will let you check if a file is in use

{code}

Function Example()
Dim FileName As String
FileName = "c:\text.txt"

Select Case isFileInUse(FileName)
Case False
MsgBox "NOT in use!"
Case True
MsgBox FileName & " is in use!"
Case -2
MsgBox "Unable to determine if file " & FileName & " is in use!"
Case -3
MsgBox FileName & " Not Found:"
Case Else
' So Long and Thanks for the Fish
End Select


End Function



Function isFileInUse(ByVal sFileName As String) As Integer
'Returns False (0) if file exists and can be opened
'Returns True (-1) if files exists but cannot be opened
'Returns -2 if file exists but no file handles available
'Returns -3 if file does not exist
Dim nFileNum As Integer

isFileInUse = False 'assume not in use

If Dir$(sFileName, ATTR_NORMAL) = "" Then GoTo noSuchFile

On Error GoTo noFileHandles
nFileNum = FreeFile()

On Error GoTo inUse
Open sFileName For Binary Access Read Lock Read Write As nFileNum
Close nFileNum

GoTo endFunc

noSuchFile:
isFileInUse = -3
Exit Function

inUse:
isFileInUse = True
Exit Function

noFileHandles:
isFileInUse = -2
Exit Function

endFunc:
End Function
{code}
---------------------------



(defun botsbuildbots() (botsbuildbots))
0 Likes