打开Excel文件并检查它是否为只读

时间:2013-07-22 15:37:39

标签: vb.net excel file

我需要在尝试写入之前检查Excel文件是否只读。这是我的代码:

  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

这是一个例外:

If GetAttr(UnapprovedFileName) And vbReadOnly Then   

例外情况是“文件”East.xlsx“找不到”。但是,文件打开,所以确实存在。我以为我需要在没有路径的情况下参考文件,但显然我有点偏离这里。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

解决方案:

If StatVar.xlApp.ActiveWorkbook.ReadOnly = True Then