2014-07-09 79 views
-1

我正在使用下面的代碼來檢查一些文件是否打開並從它們獲取數據,否則打開它們。當我用打開的文件運行程序時,會出現'下標超出範圍'的錯誤。如何檢查文件是否打開並使用它們,如果不打開它們?

Sub ReadDatafromOTWK() 
    'On Error Resume Next 
    Dim path1 As String 
    Dim path2 As String 
    Dim TWb As Workbook 
    Set TWb = ThisWorkbook 
    Dim OWb1 As Workbook 
    Dim OWb2 As Workbook 
    Dim Curdir As String 
    'Clear data 

    TWb.Sheets("OT WK").Range("B7:F1048576").Select 
    Selection.ClearContents 
    Range("B7").Select 
    Curdir = ActiveWorkbook.path 
    path1 = Curdir & "\" & TWb.Sheets("Instruction").Range("B5") 
    path2 = Curdir & "\" & TWb.Sheets("Instruction").Range("B6") 
    'Check if the file is opened 

    If IsFileOpen(path1) Then 
     ' Display a message stating the file in use. 
     MsgBox "File already in use!" 
     ' 
     ' Error the line bellow 
     Set OWb1 = Workbooks(path1) 
     OWb1.Activate 
     'GoTo 100 
    Else 
     ' Display a message stating the file is not in use. 
     'MsgBox "File not in use!" 
     ' Open the file in Microsoft Excel. 
     Set OWb1 = Workbooks.Open(path1) 
     OWb1.Activate 
     'GoTo 100 

    End If 
End Sub 

Function IsFileOpen(filename As String) 
    Dim filenum As Integer, errnum As Integer 

    On Error Resume Next ' Turn error checking off. 
    filenum = FreeFile() ' Get a free file number. 
    ' Attempt to open the file and lock it. 
    Open filename For Input Lock Read As #filenum 
    Close filenum   ' Close the file. 
    errnum = Err   ' Save the error number that occurred. 
    On Error GoTo 0  ' Turn error checking back on. 

    ' Check to see which error occurred. 
    Select Case errnum 

     ' No error occurred. 
     ' File is NOT already open by another user. 
     Case 0 
     IsFileOpen = False 

     ' Error number for "Permission Denied." 
     ' File is already opened by another user. 
     Case 70 
      IsFileOpen = True 

     ' Another error occurred. 
     Case Else 
      Error errnum 
    End Select 

End Function 
+0

哪條線導致錯誤? (當你遇到問題時你應該做的第一件事就是註釋掉「關閉錯誤檢查」這一行,就像你在「IsFileOpen()」開頭的那樣)。 –

+0

'Set OWb1 = Workbooks( path1)'錯誤時什麼是path1? – dcromley

+0

可能的重複[檢測Excel工作簿是否已經打開(使用VBA)](http://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open-using-vba) – hnk

回答

0

我不認爲你可以使用全路徑名來指代一個打開的工作簿與工作簿屬性 - 但只有它的名字

相關問題