Dim xlApp As Excel.Application '定義EXCEL類
Dim xlBook As Excel.Workbook '定義工件簿類
Dim xlsheet As Excel.Worksheet '定義工作表類
Private Sub Command1_Click() '打開EXCEL過程
If Dir("D:\temp\excel.bz") = "" Then '判斷EXCEL是否打開
Set xlApp = CreateObject("Excel.Application") '創(chuàng)建EXCEL應(yīng)用類
xlApp.Visible = True '設(shè)置EXCEL可見
Set xlBook = xlApp.Workbooks.Open("D:\temp\bb.xls") '打開EXCEL工作簿
Set xlsheet = xlBook.Worksheets(1) '打開EXCEL工作表
xlsheet.Activate '激活工作表
xlsheet.Cells(1, 1) = "abc" '給單元格1行駛列賦值
xlBook.RunAutoMacros (xlAutoOpen) 運(yùn)行EXCEL中的啟動(dòng)宏
Else
MsgBox ("EXCEL已打開")
End If
End Sub
Private Sub Command2_Click()
If Dir("D:\temp\excel.bz") <> "" Then '由VB關(guān)閉EXCEL
xlBook.RunAutoMacros (xlAutoClose) '執(zhí)行EXCEL關(guān)閉宏
xlBook.Close (True) '關(guān)閉EXCEL工作簿
xlApp.Quit '關(guān)閉EXCEL
End If
Set xlApp = Nothing '釋放EXCEL對(duì)象
End
End Sub
Sub auto_open()
Open "d:\temp\excel.bz" For Output As #1 '寫標(biāo)志文件
Close #1
End Sub
Sub auto_close()
Kill "d:\temp\excel.bz" '刪除標(biāo)志文件
End Sub
4、運(yùn)行VB程序,點(diǎn)擊EXCEL按鈕可以打開EXCEL系統(tǒng),打開EXCEL系統(tǒng)后,VB程序和EXCEL分別屬兩個(gè)不同的應(yīng)用系統(tǒng),均可同時(shí)進(jìn)行操作,由于系統(tǒng)加了判斷,因此在VB程序中重復(fù)點(diǎn)擊EXCEL按鈕時(shí)會(huì)提示EXCEL已打開。如果在EXCEL中關(guān)閉EXCEL后再點(diǎn)EXCEL按鈕,則會(huì)重新打開EXCEL。而無論EXCEL打開與否,通過VB程序均可關(guān)閉EXCEL。這樣就實(shí)現(xiàn)了VB與EXCEL的無縫連接。Public Function OutputToExcel(Optional Rs_Data As adodb.Recordset, Optional Cn As adodb.Connection, Optional strSQL As String)
Dim Irowcount As Integer
Dim Icolcount As Integer
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlQuery As Excel.QueryTable
If Rs_Data Is Nothing Then
If Cn Is Nothing Or strSQL = "" Then
Exit Function
End If
Set Rs_Data = New adodb.Recordset
With Rs_Data
If .State = adStateOpen Then
.Close
End If
.ActiveConnection = Cn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockReadOnly
.Source = strSQL
.Open
End With
End If
With Rs_Data
If .RecordCount < 1 Then
'MsgBox ("沒有記錄!")
Exit Function
End If
'記錄總數(shù)
Irowcount = .RecordCount
'字段總數(shù)
Icolcount = .Fields.Count
End With
Set xlApp = CreateObject("Excel.Application")
Set xlBook = Nothing
Set xlSheet = Nothing
Set xlBook = xlApp.Workbooks().Add
Set xlSheet = xlBook.Worksheets("sheet1")
xlApp.Visible = True
'添加查詢語句,導(dǎo)入EXCEL數(shù)據(jù)
Set xlQuery = xlSheet.QueryTables.Add(Rs_Data, xlSheet.Range("a1"))
With xlQuery
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
End With
xlQuery.FieldNames = True '顯示字段名
xlQuery.Refresh
xlApp.Application.Visible = True
Set xlApp = Nothing '"交還控制給Excel
Set xlBook = Nothing
Set xlSheet = Nothing
End Function