Eric J
Eric J

Reputation: 247

Open Excel file and check if it's read only

I need to check if an Excel file is read only before trying to write to it. Here's my code:

  Private Sub ButtonTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonTest.Click
    Dim UnapprovedAcctFile As String = "W:\TOM\ERIC\Award_Letters\Accounting Files\Unapproved\" & StatVar.xlApp.Sheets("New Calculator Input").Range("D30").Value & ".xlsx"
    Dim UnapprovedFileName = StatVar.xlApp.Sheets("New Calculator Input").Range("D30").Value & ".xlsx" 
    If Not IO.File.Exists(UnapprovedAcctFile) Then
        MessageBox.Show("Could not locate the accounting file for this school. Please contact an administrator for assistance.")
        Exit Sub
    Else
        StatVar.xlWBUnapprovedAcctFile = StatVar.xlApp.Workbooks.Open(UnapprovedAcctFile)
        If GetAttr(UnapprovedFileName) And vbReadOnly Then
            MessageBox.Show("File is read only.")
        End If
    End If
   End Sub

It's throwing an exception here:

If GetAttr(UnapprovedFileName) And vbReadOnly Then   

The exception is 'File "East.xlsx" not found.' However, the file opens, so it does indeed exist. I thought I'd need to refer to the file without the path, but apparently I'm a little off here. Any advice?

Upvotes: 3

Views: 2739

Answers (1)

Eric J
Eric J

Reputation: 247

Solution:

If StatVar.xlApp.ActiveWorkbook.ReadOnly = True Then

Upvotes: 3

Related Questions