vb.net Office365 sharepoint check file open by user

Viewed 106

I have the following script to access an excel file from office365 Sharepoint.

dim objApp2 As Excel.Application
dim objBook2 As Excel._Workbook
dim objBooks2 As Excel.Workbooks
dim objSheets2 As Excel.Sheets
dim objSheet2 As Excel._Worksheet

link="sharepointlink"
objApp2 = New Excel.Application()
objBooks2 = objApp2.Workbooks
objBook2 = objBooks2.Open(link, [ReadOnly]:=False)
objSheets2 = objBook2.Worksheets
ws2 = objSheets2("Data")
Dim valoare As Integer
valoare = Int(ws2.Range("a1").Value)
ws2.Range("a1").Value = valoare + 1
objBook2.SaveAs()
objBook2.Close(False)

I have a problem: If someone accesses my link and opens the file, either on Sharepoint or opened locally, I get an error when trying to close the object or save the file.

How can I check if the file is opened by someone when I try to save, or is there another way to access the file?

1 Answers

Welcome to the site. The ReadOnly property should tell you if another person has it open, especially when you said you want it NOT to be. You may ultimately need to switch to a shared workbook, but this should do the trick.

dim objApp2 As Excel.Application
dim objBook2 As Excel._Workbook
dim objBooks2 As Excel.Workbooks
dim objSheets2 As Excel.Sheets
dim objSheet2 As Excel._Worksheet

link="sharepointlink"
If IsFileInUse(link) then
        MsgBox "Cannot update Excel file"
        Exit Sub 'End
End If
objApp2 = New Excel.Application()
objBooks2 = objApp2.Workbooks
objBook2 = objBooks2.Open(link, [ReadOnly]:=False)
objSheets2 = objBook2.Worksheets
ws2 = objSheets2("Data")
Dim valoare As Integer
valoare = Int(ws2.Range("a1").Value)
ws2.Range("a1").Value = valoare + 1
objBook2.SaveAs()
objBook2.Close(False)



Public Function IsFileInUse(sFile As String) As Boolean
    Try
        Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
        End Using
    Catch Ex As Exception
        Return True
    End Try
    Return False
End Function
Related