I want to check if C:\Data.xlsb is already open or not.
I have got following code from here How to tell if a certain Excel file is open using VB.NET?
Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter
Dim sw As StreamWriter = nothing
Try
sw = New StreamWriter(path)
Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
REM locked, return nothing
End Try
Return sw
End Function
But I dont know how to use the code above.
I prefer sub instead of function.
Best regards.
To use this code, you would use the function as in the following example:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OpenUnlockedFile("C:\Data.xlsb") Is Nothing Then
MessageBox.Show("File is locked")
End If
End Sub
Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter
Dim sw As StreamWriter = Nothing
Try
sw = New StreamWriter(path)
Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
REM locked, return nothing
End Try
Return sw
End Function
End Class
The function, OpenUnlockedFile("C:\Data.xlsb") is run whenever you press Button1 (in this example). If the function is run and it returns Nothing, then you will know the file is locked.
Please note that you will also need
Imports System.IO
for this example to work.