Ši pamoka apims būdus, kaip importuoti duomenis iš „Excel“ į prieigos lentelę, ir būdus, kaip eksportuoti „Access“ objektus (užklausas, ataskaitas, lenteles ar formas) į „Excel“.
Importuokite „Excel“ failą į prieigą
Norėdami importuoti „Excel“ failą į „Access“, naudokite acImport variantas DoCmd.TransferSheetsheet :
DoCmd.TransferSheetsheet acImport, acSpreadsheetTypeExcel12, "Table1", "C: \ Temp \ Book1.xlsx", tiesa
Arba galite naudoti DoCmd.TransferText Norėdami importuoti CSV failą:
DoCmd.TransferText acLinkDelim,, "Table1", "C: \ Temp \ Book1.xlsx", tiesa
Importuokite „Excel“ į prieigos funkciją
Šią funkciją galima naudoti norint importuoti „Excel“ failą arba CSV failą į prieigos lentelę:
Viešoji funkcija ImportFile (failo pavadinimas kaip eilutė, HasFieldNames kaip loginis, lentelės pavadinimas kaip eilutė) kaip loginis „Pavyzdinis naudojimo būdas: skambinkite ImportFile („ Pasirinkite „Excel“ failą “,„ Excel failai “,„*.xlsx “,„ C: \ “, tiesa , Tiesa, "ExcelImportTest", tiesa, tiesa, klaidinga, tiesa) dėl klaidos GoTo err_handler If (Teisė (failo pavadinimas, 3) = "xls") arba ((dešinė (failo pavadinimas, 4) = "xlsx")) Tada DoCmd. TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, TableName, Filename, blnHasFieldNames End If If (Right (Filename, 3) = "csv") Tada DoCmd.TransferText acLinkDelim,, TableName, Filename, True End If Exit_Thing: 'Clean up' „Excel“ lentelė jau egzistuoja … ir ištrinkite ją, jei taip. Skaičius = 3073) Ir errCount <3 Tada errCount = errCount + 1 ElseIf Err.Number = 3127 Tada MsgBox "Visų skirtukų laukai yra vienodi. Įsitikinkite, kad kiekvienas lapas turi tikslius stulpelių pavadinimus, jei norite importuoti kelis “, vbCritical,„ MultiSheets not identiškas “ImportFile = False GoTo Exit_Thing Else MsgBox Err.Number &" - "& Err.Description ImportFile = False GoTo Exit_Thing Resume End If End Function
Funkciją galite iškviesti taip:
Privatus antrinis ImportFile_Example () Skambinti VBA_Access_ImportExport.ImportFile („C: \ Temp \ Book1.xlsx“, tiesa, „Imported_Table_1“) Pabaiga
Pasiekite „VBA Export“ į naują „Excel“ failą
Norėdami eksportuoti „Access“ objektą į naują „Excel“ failą, naudokite DoCmd.OutputTo metodas arba DoCmd.TransferSpreadsheet metodas:
Eksportuokite užklausą į „Excel“
Ši VBA kodo eilutė eksportuos užklausą į „Excel“ naudodami „DoCmd“.
DoCmd.OutputTo acOutputQuery, "Query1", acFormatXLSX, "c: \ temp \ ExportedQuery.xls"
Arba galite naudoti DoCmd.TransferSpreadsheet metodą:
DoCmd.TransferSpreadsheetheet acExport, acSpreadsheetTypeExcel8, "Query1", "c: \ temp \ ExportedQuery.xls", tiesa
Pastaba: Šis kodas eksportuojamas į XLSX formatą. Vietoj to galite atnaujinti argumentus ir eksportuoti juos į CSV arba XLS failo formatą (pvz. acFormatXLSX į „ACFormatXLS“).
Eksportuoti ataskaitą į „Excel“
Ši kodo eilutė eksportuos ataskaitą į „Excel“ naudodami „DoCmd“. OutputTo:
DoCmd.OutputTo acOutputReport, „Report1“, „acFormatXLSX“, „c: \ temp \ ExportedReport.xls“
Arba galite naudoti DoCmd.TransferSpreadsheet metodą:
DoCmd.TransferSheetsheetheet acExport, acSpreadsheetTypeExcel8, "Report1", "c: \ temp \ ExportedReport.xls", tiesa
Eksportuoti lentelę į „Excel“
Ši kodo eilutė eksportuos lentelę į „Excel“ naudodami „DoCmd“. OutputTo:
DoCmd.OutputTo acOutputTable, "Table1", acFormatXLSX, "c: \ temp \ ExportedTable.xls"
Arba galite naudoti DoCmd.TransferSpreadsheet metodą:
DoCmd.TransferSpreadsheetheet acExport, acSpreadsheetTypeExcel8, "Table1", "c: \ temp \ ExportedTable.xls", tiesa
Eksportuoti formą į „Excel“
Ši kodo eilutė eksportuos formą į „Excel“ naudodami „DoCmd“.
DoCmd.OutputTo acOutputForm, „Form1“, „acFormatXLSX“, „c: \ temp \ ExportedForm.xls“
Arba galite naudoti DoCmd.TransferSpreadsheet metodą:
DoCmd.TransferSheetsheetheet acExport, acSpreadsheetTypeExcel8, "Form1", "c: \ temp \ ExportedForm.xls", tiesa
Eksportuoti į „Excel“ funkcijas
Šios vienos eilutės komandos puikiai tinka eksportuoti į naują „Excel“ failą. Tačiau jie negalės eksportuoti į esamą darbo knygą. Žemiau esančiame skyriuje pristatome funkcijas, kurios leidžia pridėti eksportą prie esamo „Excel“ failo.
Žemiau mes įtraukėme kai kurias papildomas funkcijas, skirtas eksportuoti į naujus „Excel“ failus, įskaitant klaidų tvarkymą ir dar daugiau.
Eksportuoti į esamą „Excel“ failą
Aukščiau pateikti kodo pavyzdžiai puikiai tinka eksportuoti „Access“ objektus į naują „Excel“ failą. Tačiau jie negalės eksportuoti į esamą darbo knygą.
Norėdami eksportuoti „Access“ objektus į esamą „Excel“ darbaknygę, sukūrėme šią funkciją:
Viešoji funkcija „AppendToExcel“ („strObjectType“ kaip eilutė, „strObjectName“ kaip eilutė, „strSheetName“ kaip eilutė, „strFileName“ kaip eilutė) „Dim rst“ kaip DAO. As Long = -4161 Const xlCenter As Long = -4108 Const xlBottom As Long = -4107 Const xlContinuous As Long = 1 Pasirinkite atvejį strObjectType Case "Table", "Query" Set rst = CurrentDb.OpenRecordset (strObjectName, dbOpenDynaset, dbSeeChanges) Byla "Form" Set rst = Forms (strObjectName) .RecordsetClone Case "Report" Set rst = CurrentDb.OpenRecordset (Reports (strObjectName) .RecordSource, dbOpenDynaset, dbSeeChanges) Pabaiga Pasirinkite If rst.RecordCount = 0 Tada Msg bebox " ".," vbInformation, GetDBTitle Else On Error Resume Next Set Nustatykite xlWBk = ApXL.Workbooks.Open (strFil eName) Nustatykite xlWSh = xlWBk.Sheets.Add xlWSh.Name = Left (strSheetName, 31) xlWSh.Range ("A1"). Pasirinkite Do Do intCount = rst.fields.Count ApXL.ActiveCell = rst.fields (intCount). Pavadinimas ApXL.ActiveCell.Offset (0, 1). Pasirinkite intCount = intCount + 1 Loop rst.MoveFirst xlWSh.Range ("A2"). CopyFromRecordset rst Su ApXL .Range ("A1"). Pasirinkite .Range (.Selection, .Selection.End (xlToRight)). Pasirinkite .Selection.Interior.Pattern = xlSolid .Selection.Interior.PatternColorIndex = xlAutomatic .Selection.Interior.TintAndShade = -0.25 .Selection.Interior.PatternTintAndSelection xlNone .Selection.AutoFilter .Cells.EntireColumn.AutoFit .Cells.EntireRow.AutoFit .Range ("B2"). Pasirinkite .ActiveWindow.FreezePanes = True .ActiveSheet.Cells.Select .ActiveSheet.Cells.WrapTextSalse = FalseC. .EntireColumn.AutoFit xlWSh.Range ("A1"). Pasirinkite .Visible = True End su 'xlWB.Close True' Set xlWB = Nieko 'ApXL.Quit' Set ApXL = Nieko nesibaigia, jei funkcija
Funkciją galite naudoti taip:
Private Sub AppendToExcel_Example () Skambinti VBA_Access_ImportExport.ExportToExcel ("Table", "Table1", "VBASheet", "C: \ Temp \ Test.xlsx") Pabaiga
Atkreipkite dėmesį, kad jūsų prašoma apibrėžti:
- Ką išvesti? Lentelė, ataskaita, užklausa arba forma
- Objekto pavadinimas
- Išvesties lapo pavadinimas
- Išvesties failo kelias ir pavadinimas.
Eksportuokite SQL užklausą į „Excel“
Vietoj to galite eksportuoti SQL užklausą į „Excel“ naudodami panašią funkciją:
Viešoji funkcija „AppendToExcelSQLStatemet“ (strsql kaip eilutė, strSheetName kaip eilutė, strFileName kaip eilutė) Dim strQueryName kaip eilutė Dim ApXL kaip „Excel“. Taikymas Dim xlWBk Kaip „Excel“. Darbo knygos Dim xlWSh kaip „Excel“. Darbo lapas Dim intCount As Integer Const = l xlBottom As Long = -4107 Const xlVAlignCenter = -4108 Const xlContinuous As Long = 1 Dim qdf Kaip DAO.QueryDef Dim rst As DAO.Recordset strQueryName = "tmpQueryToExportToExcel" Jei ObjectExists ("QueryNe.Quue Strue" Pabaiga Jei nustatytas qdf = CurrentDb.CreateQueryDef (strQueryName, strsql) Nustatykite rst = CurrentDb.OpenRecordset (strQueryName, dbOpenDynaset) Jei rst.RecordCount = 0 Tada MsgBox "Nėra įrašų, kuriuos reikia eksportuoti.", VbInformation, Kitas OnDBT ApXL = GetObject (, "Excel.Application") Jei Err.Number 0 tada nustatykite ApXL = CreateObject ("Excel.Application") Pabaiga, jei Err.Clear ApXL.Visible = False Set xlWBk = ApXL.Workbooks.Open (strFileName) rinkinys xlWSh = xlWBk.Sheet s.Add xlWSh.Name = Kairė (strSheetName, 31) xlWSh.Range ("A1"). Pasirinkite Daryti iki intCount = rst.fields.Count ApXL.ActiveCell = rst.fields (intCount) .Pavadinimas ApXL.ActiveCell.Offset ( 0, 1). Pasirinkite intCount = intCount + 1 Loop rst.MoveFirst xlWSh.Range ("A2"). CopyFromRecordset rst Su ApXL .Range ("A1"). Pasirinkite .Range (.Selection, .Selection.End (xlToRight) ) .Pasirinkite .Selection.Interior.Pattern = xlSolid .Selection.Interior.PatternColorIndex = xlAutomatic .Selection.Interior.TintAndShade = -0.25 .Selection.Interior.PatternTintAndShade = 0 .Selection.Bertern.Light.Line .EntireColumn.AutoFit .Cells.EntireRow.AutoFit .Range ("B2"). Pasirinkite .ActiveWindow.FreezePanes = True .ActiveSheet.Cells.Select .ActiveSheet.Cells.WrapText = Netiesa .ActiveSheet.Cells.EntireColge.Skolona.Fol. ("A1"). Pasirinkite .Visible = True End su 'xlWB.Close True' Set xlWB = Nothing 'ApXL.Quit' Set ApXL = Nothing End if End Function
Vadinasi taip:
Private Sub AppendToExcelSQLStatemet_Example () Skambinti VBA_Access_ImportExport.ExportToExcel ("SELECT * FROM Table1", "VBASheet", "C: \ Temp \ Test.xlsx") Pabaiga
Kur jūsų prašoma įvesti:
- SQL užklausa
- Išvesties lapo pavadinimas
- Išvesties failo kelias ir pavadinimas.
Funkcija eksportuoti į naują „Excel“ failą
Šios funkcijos leidžia eksportuoti „Access“ objektus į naują „Excel“ darbaknygę. Jos gali būti naudingesnės nei paprastos eilutės dokumento viršuje.
Viešoji funkcija ExportToExcel (strObjectType kaip eilutė, strObjectName kaip eilutė, pasirinktinai strSheetName kaip eilutė, pasirinktinai strFileName kaip eilutė) Dim rst kaip DAO.Recordset Dim ApXL kaip objektas Dim xlWBk kaip objektas Dim xlWSh kaip objektas Dim intCl = Integer Const 4161 Const xlCenter As Long = -4108 Const xlBottom As Long = -4107 Const xlContinuous As Long = 1 On Error GoTo ExportToExcel_Err DoCmd.Hourglass True Select Case , dbSeeChanges) Byla "Forma" Nustatykite rst = Forms (strObjectName) .RecordsetClone Case "Report" Nustatykite rst = CurrentDb.OpenRecordset (Reports (strObjectName) .RecordSource, dbOpenDynaset, dbSeeChanges) Pabaiga Pasirinkite If rst.RecordsB = 0 įrašai, kuriuos reikia eksportuoti. ", vbInformation, GetDBTitle DoCmd.Hourglass False Else On Error Resume Next Set Klaida. Išvalyti klaidą GoTo ExportToExcel_Err Nustatykite xlWBk = ApXL.Workbooks.Add ApXL.Visible = False Set xlWSh = xlWBk.Worksheets ("Sheet1") Jei Len (strSheetName)> 0 Tada xlWSh.Name = Left (strSheet xPavardės pavadinimas, .Range ("A1"). Pasirinkite Do Do till intCount = rst.fields.Count ApXL.ActiveCell = rst.fields (intCount) .Pavadinimas ApXL.ActiveCell.Offset (0, 1). Pasirinkite intCount = intCount + 1 Loop rst. „MoveFirst xlWSh.Range“ („A2“). „CopyFromRecordset“ pirmą kartą naudojant „ApXL .Range“ („A1“). Pasirinkite .Range (.Selection, .Selection.End (xlToRight)). Pasirinkite .Selection.Interior.Pattern = xlSolid .Selection. Interior.PatternColorIndex = xlAutomatic .Selection.Interior.TintAndShade = -0.25 .Selection.Interior.PatternTintAndShade = 0 .Selection.Borders.LineStyle = xlNone .Selection.AutoFilter .Cells.EntireColumn.EntireColumn.Auto. B2 "). Pasirinkite .ActiveWindow.FreezePanes = True .ActiveSheet.Cells.Select .ActiveSheet.Cells.WrapText = False .ActiveSheet.Cells.EntireColumn.AutoFit xlWSh.Range (" A1 "). Pasirinkite .Visible = True End Wi trečiasis bandymas: Jei „FileExists“ (strFileName), tada nužudykite strFileName End If strFileName "" Tada xlWBk.SaveAs strFileName, FileFormat: = 56 End If rst.Close Set rst = Nothing DoCmd.Hourglass False End If ExportToExcel_Exit ExChx ExportToExcel_Err: DoCmd.SetWarnings True MsgBox Err.Description, vbExclamation, Err.Number DoCmd.Hourglass False Resume ExportToExcel_Exit End Function
Funkciją galima pavadinti taip:
Privatus antrinis eksportasToExcel_Example () Skambinti VBA_Access_ImportExport.ExportToExcel („Lentelė“, „1 lentelė“, „VBASheet“) Pabaiga