2014-02-26 62 views
1

我編寫了下面的過程來檢查打開的Excel實例,然後檢查是否打開了特定的工作簿,是否打開工作簿,然後轉到選定的工作表。重寫程序以搜索打開的Excel工作簿

該程序正常,但我並不特別滿意我寫的方式。例如,在以下幾行中,該過程將檢查工作簿是否已打開,如果未打開,則會跳出該路徑並使用Catch將其打開。

Dim xlWBName As String = "2011.1004.Compensation Template" 
    Dim xlBookPath As String = Path.Combine(Directory.GetCurrentDirectory()) 

    xlApp.Visible = True 

    Try 

     'get the opened workbook 

     xlBook = xlApp.Workbooks(xlWBName & ".xlsx") 

    Catch ex As Exception 

     'open it 
     xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx") 

    End Try 

我不想使用Catch,就好像它是不是已經打開,打開工作簿我的方式。我寧願將它用作真正的例外,例如工作簿不在目錄中。我的問題是,如何重新編寫這個程序,以更好地做我想做的事情。這裏是我的整個過程:

公用Sub GoToSheets(SHEETNAME作爲字符串)

Cursor.Current = Cursors.AppStarting 

frmPleaseWait.Show() 

Try 
    'get an existing excel.application object 
    xlApp = CType(GetObject(, "Excel.Application"), Application) 

Catch ex As Exception 
    'no existing excel.application object - create a new one 

    xlApp = New Excel.Application 

End Try 

Dim xlWBName As String = "2011.1004.Compensation Template" 
Dim xlBookPath As String = Path.Combine(Directory.GetCurrentDirectory()) 

xlApp.Visible = True 

Try 

    'get the opened workbook 

    xlBook = xlApp.Workbooks(xlWBName & ".xlsx") 

Catch ex As Exception 

    'open it 
    xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx") 

End Try 

Try 

    xlSheet = CType(CType(xlBook.Sheets(sheetName), Excel.Worksheet), Excel.Worksheet) 

    xlSheet.Activate() 
    frmPleaseWait.Close() 

    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) 

    GC.Collect() 
    GC.WaitForPendingFinalizers() 
    GC.Collect() 
    GC.WaitForPendingFinalizers() 

    'Show curser waiting 
    Cursor.Current = Cursors.WaitCursor 

Catch ex As Exception 

    'Catch any other exceptions here 
    MessageBox.Show("An exception occurred while processing the file" & vbNewLine & ex.GetType.ToString, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error) 

End Try 

末次

回答

1

你要試圖找到一個Excel的實例唯一的例外是CType可能是因爲失敗並投擲InvalidCastException。你或許可以避免通過避免投(最初):通過他們

Dim xlObject As Object 

Try 
    'get an existing excel.application object 
    xlObject = GetObject(, "Excel.Application") 
Catch ex As Exception 
    ' Some other exception now 

End Try 

If Not xlObject Is Nothing Then ' Found something, make the cast 
    xlApp = CType(xlObject, Application) 
Else ' Did not find anything, create new instance 
    xlApp = New Excel.Application 
End If 

並檢查工作簿存在,只是循環,並檢查他們的名字:

Dim isWbOpen As Boolean 
For i As Integer = 0 To xlApp.Workbooks.Count - 1 
    If xlApp.Workbooks(i).Name = xlWBName Then 
     isWbOpen = True 
     Exit For 
    End If 
Next 

If isWbOpen Then 
    xlBook = xlApp.Workbooks(xlWBName & ".xlsx") 
Else 
    xlBook = xlApp.Workbooks.Open(xlBookPath & "\" & xlWBName & ".xlsx") 
End If 
+0

謝謝,不僅做到了解決我的問題,它實際上運行得更快。 –