Você está na página 1de 2

Usando a DAO e automao OLE veja como converter uma tabela em uma planilha Excel.

Vo c vai precisar ter o Excel 5.0 ou superior e o Visual Basic 5.0. Crie um novo projeto no VB Insira um botao de commando (command1 ) e uma label (label1) no form1. Referencie a "Microsoft Excel Object Library" e tambm o "Microsoft DAO Object Lib rary." Insira o cdigo a seguir na seo General Declarations do form1 Private Type ExlCell row As Long col As Long End Type Private Sub CopyRecords(rs As Recordset, ws As Worksheet, _ StartingCell As ExlCell) Dim SomeArray() As Variant Dim row As Long, col As Long Dim fd As Field rs.MoveLast ReDim SomeArray(rs.RecordCount + 1, rs.Fields.Count) ' Copia as colunas do cabecalho para um vetor col = 0 For Each fd In rs.Fields SomeArray(0, col) = fd.Name col = col + 1 Next ' copia o rs par um vetor rs.MoveFirst For row = 1 To rs.RecordCount - 1 For col = 0 To rs.Fields.Count - 1 SomeArray(row, col) = rs.Fields(col).Value ' O Excel no suporta valores NULL em uma clula. If IsNull(SomeArray(row, col)) Then _ SomeArray(row, col) = "" Next rs.MoveNext Next ws.Range(ws.Cells(StartingCell.row, StartingCell.col), _ ws.Cells(StartingCell.row + rs.RecordCount + 1, _ StartingCell.col + rs.Fields.Count)).Value = SomeArray End Sub Sub Form_Load() Label1.AutoSize = True Label1.Caption = "Ready" Label1.Refresh End Sub Sub Dim Dim Dim Dim Dim Command1_Click() oExcel as Object objExlSht As Object ' OLE automation object stCell As ExlCell db As Database ' Database object Sn As Recordset ' Recordset

MousePointer = vbHourglass ' Muda o ponteiro do mouse Label1.Caption = "Criando um objeto Object" Label1.Refresh Set oExcel = CreateObject("Excel.Application") oExcel.WorkBooks.Add Set objExlSht = oExcel.ActiveWorkbook.Sheets(1) ' Open the database: Label1.Caption = "Abrindo o banco de dados" Label1.Refresh Set db = OpenDatabase("BIBLIO.MDB") ' Define o nome dos campos Label1.Caption = "Criando SnapShot" Label1.Refresh Set Sn = db.OpenRecordset("Titles", dbOpenSnapshot) ' Start fill range at A1 stCell.row = 1 stCell.col = 1 Label1.Caption = "Inserindo os dados na planilha" Label1.Refresh CopyRecords Sn, objExlSht, stCell ' Save the spreadsheet: Label1.Caption = "Salvando a planilha" Label1.Refresh objExlSht.SaveAs "C:\\TITLES.XLS" Label1.Caption = "Encerrando o Excel" Label1.Refresh objExlSht.Application.Quit ' Clean up: Label1.Caption = "Limpando o ambiente" Label1.Refresh Set objExlSht = Nothing ' remove a variavel objeto Set oExcel = Nothing ' remove a variavel objeto Set Sn = Nothing ' reomove a variavel objeto Set db = Nothing ' reomove a variavel objeto MousePointer = vbDefault ' Restaura o ponteiro do mouse. Label1.Caption = "OK ! " Label1.Refresh End Sub objExlSht.SaveAs "C:\Documents and Settings\Israel\Desktop\Listagem De Itens.XLS "

Você também pode gostar