某些時候需要打開Excel文件來獲取或者寫入數據,但又不希望跳出打開的Excel文件窗口,可以用下面的代碼:
Dim eb As New excel.Application, wb as excel.Workbook
Set wb = eb.Application.Workbooks.Open(FileName:=nameOfFile, ReadOnly:=False) ' open
' do your work
wb.Close True ' save and close
原理:New Excel.Application新建了一個Excel實例,這個實例默認不可見。具體而言,獲取Excel.Application實例有兩種方式:
Dim eb As Excel.Application
Set eb = CreateObject(, "Excel.Application")
' 新建Excel實例,同dim eb as new Excel.Application
Set eb = GetObject(, "Excel.Application")
' 從Windows環境獲取Excel實例,如果當前沒有打開的Excel窗口,將出現錯誤
如果對是否後台打開沒有要求的話,最好結合上面兩種方式獲取Excel實例:
' 獲取Excel實例,如果當前已經有excel窗口,則直接獲取當前實例,否則新建實例
Function GetExcelApp() As Excel.Application
On Error Resume Next
Set GetExcelApp = GetObject(, "Excel.Application")
If Err.Number > 0 Then Err.Clear: Set GetExcelApp = New Excel.Application
End Function