某些时候需要打开 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
Q. E. D.