首先要在VB中引用EXCEL。代码参考如下:
Dim xlapp As Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Set xlapp = New Excel.Application
xlapp.Workbooks.Open (App.Path & "\文件.xls")
Set xlbook = xlapp.Workbooks(1)
Set xlsheet = xlbook.Worksheets("sheet1")
首先要在VB中引用EXCEL。代码参考如下:
Dim xlapp As Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Set xlapp = New Excel.Application
xlapp.Workbooks.Open (App.Path & "\文件.xls")
Set xlbook = xlapp.Workbooks(1)
Set xlsheet = xlbook.Worksheets("sheet1")
DIM STR1
STR1 =xlsheet.Cells(2, 3).Value '取出Excel文件sheet1中C2的值
xlbook.Save
xlbook.Close
xlapp.Quit
If Source.RecordCount > 0 Then
TblRow = PStartTblRow
Source.MoveFirst
Do While Not Source.EOF
With Excel.Selection
.WrapText = True
End With
TblCol = PStartTblCol
For i = DataFrom To Source.Fields.Count - 1
SeCol = GetTblColString(TblCol)
Merges = SeCol & TblRow
WorkSheet.Range(Merges).Select
With Excel.Selection
.WrapText = True
End With
If IsNull(Source(i)) Then
TempValue = ""
Else
TempValue = Source(i)
End If
WorkSheet.Range(Merges).Value = TempValue
TblCol = TblCol + 1
Next i
Source.MoveNext
TblRow = TblRow + 1
Loop
Else
'MsgBox "表中没有记录", vbOKOnly + vbExclamation, "信息"
Exit Sub
End If
实际的例子:
Dim db As dao.Database
Dim rs As dao.Recordset
Dim fd As dao.Field
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim cellCnt As Integer
' Open the destination Excel workbook.
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.add
Set xlSheet = xlBook.ActiveSheet
xlBook.PrintPreview
' Open the recordset.
Set db = DBEngine.Workspaces(0).OpenDatabase(App.Path & "\bmkq.mdb")
Set rs = db.OpenRecordset("SELECT bm as 部门,xm as 姓名,gongshi as 出勤,jb as 加班,cd as 迟到,zt as 早退,wdk as 未打卡," & _
"sj as 事假,bj as 病假,cj as 产假,hj as 婚假,nj as 年假,hx as 换休,cc as 出差,gs as 工伤,qt as 其他," & _
"gongxiu as 公休,jjr as 节假日,bz as 备注 FROM yb order by xm")
' This is all it takes to copy the contents
' of the recordset into the first worksheet
' of Book1.xls.
xlSheet.Cells(1, 1).Value = Format(dtp(0), "long date") & "至" & Format(dtp(1), "long date") & "考勤汇总表"
cellCnt = 1
For Each fd In rs.Fields
Select Case fd.Type
Case dbBinary, dbGUID, dbLongBinary, dbVarBinary
' This type of data can't export to excel
Case Else
xlSheet.Cells(2, cellCnt).Value = fd.Name
xlSheet.Cells(2, cellCnt).Interior.ColorIndex = 33
xlSheet.Cells(2, cellCnt).Font.Bold = True
xlSheet.Cells(2, cellCnt).BorderAround xlContinuous
cellCnt = cellCnt + 1
End Select
Next
xlBook.Worksheets(1).Range("A3").CopyFromRecordset rs
xlApp.ActiveWindow.DisplayZeros = False
xlBook.Worksheets(1).Range("A3").Select
xlApp.Visible = True
' Clean up everything.
'xlBook.Save
'xlBook.Close False
'xlApp.Quit
rs.Close
db.Close
'Set xlBook = Nothing
'Set xlApp = Nothing
Set rs = Nothing
Set db = Nothing