Export Query to Excel file
กระทู้เก่าบอร์ด อ.Yeadram

 5,527   11
URL.หัวข้อ / URL
Export Query to Excel file

ขออนุญาติสอบถามผู้รู้ครับ
ผมไม่ค่อยเก่ง โค้ด VBA นะครับ แต่พอประยุกต์ใช้ได้ครับ
ผมต้องการ Export query ด้วยการคลิกปุ่ม export
ดังนี้ครับ
- Browse โฟล์เดอร์ที่ต้องการบันนทึกไฟล์ ได้
- ตั้งชื่อไฟล์ได้

อยากทราบวิธีการ 2 แบบ คือ
- export หลาย query เป็น Excel ไฟล์เดียว หลายชีท
- exprot 1 query : 1 excel

ผมต้องเขียนโค้ดอะไรบ้างครับ
ขอบคุณครับผม


11 Reply in this Topic. Dispaly 1 pages and you are on page number 1

1 @R20409
ทั้งหมดทำได้โดยแค่คลิกขวาที่คิวรี่ เลือก Export - เลือกโฟลเดอร์ - เลือกประเภทของไฟล์เป็น Excel - เลือกชื่อไฟล์เดิม(ถ้าต้องการเก็บเป็น sheet ใหม่) หรือป้อนชื่อไฟล์ใหม่(ถ้าต้องการเก็บเป็น sheet แรกใน workbook) กรณีแรก เขาจะถามต่อว่าต้องการทับไฟล์เดิมหรือไม่ ก็ให้ตอบไม่ แล้วเขาก็จะถามชื่อ sheet ที่ต้องการเพิ่มเช้าไปครับ
2 @R20410
ของคุณครับ คุณสันติสุข
ผมหมายถึง code vba สำหรับ ทำปุ่ม export น่ะครับ
หรือคำถามผมไม่เคลียร์
3 @R20412
Browse Folder + File :
- ถ้าจะดูโค้ดแบบเรียบง่าย แต่ต้องเพิ่ม Micrsoft Office xx.xx Object Library ก็ดูที่ อ.Yeadram ตอบใน http://www.thai-access.com/yeadram_view.php?topic_id=4501

- ถ้าจะเอาโค้ดที่ไม่ต้องเพิ่ม Object Library ที่ว่าไว้
http://www.thai-access.com/yeadram_view.php?topic_id=381

Export Excel :
- DoCmd.TransferSpreadsheet acExport, , "ชื่อคิวรี่", "ชื่อพาธ+ไฟล์"
ถ้า export คิวรี่คนละตัวไปลงไฟล์เดียวกัน ก็จะถูกสร้างเป็นคนละชีทให้
4 @R20413
ผมมีตัวอย่างที่เคยทำมาให้ลองครับ ผมได้มาจากเวปนอกแตจำที่มาไม่ได้ครับ

เบื้องต้นสร้าง Module โดยใส่โค้ดตามนี้ก่อนครับ
'***************** Code Start **************
' This code was originally written by Ken Getz.
' It is not to be altered or distributed, 'except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code originally courtesy of:
' Microsoft Access 95 How-To
' Ken Getz and Paul Litwin
' Waite Group Press, 1996
' Revised to support multiple files:
' 28 December 2007

Type tagOPENFILENAME
    lStructSize As Long
    hwndOwner As Long
    hInstance As Long
    strFilter As String
    strCustomFilter As String
    nMaxCustFilter As Long
    nFilterIndex As Long
    strFile As String
    nMaxFile As Long
    strFileTitle As String
    nMaxFileTitle As Long
    strInitialDir As String
    strTitle As String
    Flags As Long
    nFileOffset As Integer
    nFileExtension As Integer
    strDefExt As String
    lCustData As Long
    lpfnHook As Long
    lpTemplateName As String
End Type

Declare Function aht_apiGetOpenFileName Lib "comdlg32.dll" _
    Alias "GetOpenFileNameA" (OFN As tagOPENFILENAME) As Boolean

Declare Function aht_apiGetSaveFileName Lib "comdlg32.dll" _
    Alias "GetSaveFileNameA" (OFN As tagOPENFILENAME) As Boolean
Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long

Global Const ahtOFN_READONLY = &H1
Global Const ahtOFN_OVERWRITEPROMPT = &H2
Global Const ahtOFN_HIDEREADONLY = &H4
Global Const ahtOFN_NOCHANGEDIR = &H8
Global Const ahtOFN_SHOWHELP = &H10
' You won't use these.
'Global Const ahtOFN_ENABLEHOOK = &H20
'Global Const ahtOFN_ENABLETEMPLATE = &H40
'Global Const ahtOFN_ENABLETEMPLATEHANDLE = &H80
Global Const ahtOFN_NOVALIDATE = &H100
Global Const ahtOFN_ALLOWMULTISELECT = &H200
Global Const ahtOFN_EXTENSIONDIFFERENT = &H400
Global Const ahtOFN_PATHMUSTEXIST = &H800
Global Const ahtOFN_FILEMUSTEXIST = &H1000
Global Const ahtOFN_CREATEPROMPT = &H2000
Global Const ahtOFN_SHAREAWARE = &H4000
Global Const ahtOFN_NOREADONLYRETURN = &H8000
Global Const ahtOFN_NOTESTFILECREATE = &H10000
Global Const ahtOFN_NONETWORKBUTTON = &H20000
Global Const ahtOFN_NOLONGNAMES = &H40000
' New for Windows 95
Global Const ahtOFN_EXPLORER = &H80000
Global Const ahtOFN_NODEREFERENCELINKS = &H100000
Global Const ahtOFN_LONGNAMES = &H200000


Function ahtCommonFileOpenSave( _
            Optional ByRef Flags As Variant, _
            Optional ByVal InitialDir As Variant, _
            Optional ByVal filter As Variant, _
            Optional ByVal FilterIndex As Variant, _
            Optional ByVal DefaultExt As Variant, _
            Optional ByVal filename As Variant, _
            Optional ByVal DialogTitle As Variant, _
            Optional ByVal hwnd As Variant, _
            Optional ByVal OpenFile As Variant) As Variant

    ' This is the entry point you'll use to call the common
    ' file open/save dialog. The parameters are listed
    ' below, and all are optional.
    '
    ' In:
    ' Flags: one or more of the ahtOFN_* constants, OR'd together.
    ' InitialDir: the directory in which to first look
    ' Filter: a set of file filters, set up by calling
    ' AddFilterItem. See examples.
    ' FilterIndex: 1-based integer indicating which filter
    ' set to use, by default (1 if unspecified)
    ' DefaultExt: Extension to use if the user doesn't enter one.
    ' Only useful on file saves.
    ' FileName: Default value for the file name text box.
    ' DialogTitle: Title for the dialog.
    ' hWnd: parent window handle
    ' OpenFile: Boolean(True=Open File/False=Save As)
    ' Out:
    ' Return Value: Either Null or the selected filename
    Dim OFN As tagOPENFILENAME
    Dim strFileName As String
    Dim strFileTitle As String
    Dim fResult As Boolean

    ' Give the dialog a caption title.
    If IsMissing(InitialDir) Then InitialDir = CurDir
    If IsMissing(filter) Then filter = ""
    If IsMissing(FilterIndex) Then FilterIndex = 1
    If IsMissing(Flags) Then Flags = 0&
    If IsMissing(DefaultExt) Then DefaultExt = ""
    If IsMissing(filename) Then filename = ""
    If IsMissing(DialogTitle) Then DialogTitle = ""
    If IsMissing(hwnd) Then hwnd = Application.hWndAccessApp
    If IsMissing(OpenFile) Then OpenFile = True
    ' Allocate string space for the returned strings.
    strFileName = Left(filename & String(256, 0), 256)
    strFileTitle = String(256, 0)
    ' Set up the data structure before you call the function
    With OFN
        .lStructSize = Len(OFN)
        .hwndOwner = hwnd
        .strFilter = filter
        .nFilterIndex = FilterIndex
        .strFile = strFileName
        .nMaxFile = Len(strFileName)
        .strFileTitle = strFileTitle
        .nMaxFileTitle = Len(strFileTitle)
        .strTitle = DialogTitle
        .Flags = Flags
        .strDefExt = DefaultExt
        .strInitialDir = InitialDir
        ' Didn't think most people would want to deal with
        ' these options.
        .hInstance = 0
        '.strCustomFilter = ""
        '.nMaxCustFilter = 0
        .lpfnHook = 0
        'New for NT 4.0
        .strCustomFilter = String(255, 0)
        .nMaxCustFilter = 255
    End With
    ' This will pass the desired data structure to the
    ' Windows API, which will in turn it uses to display
    ' the Open/Save As Dialog.
    If OpenFile Then
        fResult = aht_apiGetOpenFileName(OFN)
    Else
        fResult = aht_apiGetSaveFileName(OFN)
    End If

    ' The function call filled in the strFileTitle member
    ' of the structure. You'll have to write special code
    ' to retrieve that if you're interested.
    If fResult Then
        ' You might care to check the Flags member of the
        ' structure to get information about the chosen file.
        ' In this example, if you bothered to pass in a
        ' value for Flags, we'll fill it in with the outgoing
        ' Flags value.
        If Not IsMissing(Flags) Then Flags = OFN.Flags
        If Flags And ahtOFN_ALLOWMULTISELECT Then
            ' Return the full array.
            Dim items As Variant
            Dim value As String
            value = OFN.strFile
            ' Get rid of empty items:
            Dim i As Integer
            For i = Len(value) To 1 Step -1
              If Mid$(value, i, 1) <> Chr$(0) Then
               Exit For
              End If
            Next i
            value = Mid(value, 1, i)

            ' Break the list up at null characters:
            items = Split(value, Chr(0))

            ' Loop through the items in the "array",
            ' and build full file names:
            Dim numItems As Integer
            Dim result() As String

            numItems = UBound(items) + 1
            If numItems > 1 Then
               ReDim result(0 To numItems - 2)
               For i = 1 To numItems - 1
                    result(i - 1) = FixPath(items(0)) & items(i)
               Next i
               ahtCommonFileOpenSave = result
            Else
               ' If you only select a single item,
               ' Windows just places it in item 0.
               ahtCommonFileOpenSave = items(0)
            End If
        Else
            ahtCommonFileOpenSave = TrimNull(OFN.strFile)
        End If
    Else
        ahtCommonFileOpenSave = vbNullString
    End If
End Function

Function ahtAddFilterItem(strFilter As String, _
    strDescription As String, Optional varItem As Variant) As String

    ' Tack a new chunk onto the file filter.
    ' That is, take the old value, stick onto it the description,
    ' (like "Databases"), a null character, the skeleton
    ' (like "*.mdb;*.mda") and a final null character.

    If IsMissing(varItem) Then varItem = "*.*"
    ahtAddFilterItem = strFilter & _
               strDescription & vbNullChar & _
               varItem & vbNullChar
End Function

Private Function TrimNull(ByVal strItem As String) As String
    Dim intPos As Integer

    intPos = InStr(strItem, vbNullChar)
    If intPos > 0 Then
        TrimNull = Left(strItem, intPos - 1)
    Else
        TrimNull = strItem
    End If
End Function

Private Function FixPath(ByVal path As String) As String
    If Right$(path, 1) <> "\" Then
        FixPath = path & "\"
    Else
        FixPath = path
    End If
End Function

'************** Code End *****************







จากนั้นสร้าง Open/Save Dialog (ใช้ Browse ไฟล์ หรือ save File) ที่ต้องการ

'open dialog for Export
Function ExportFile()
    Dim strFilter As String
    Dim lngFlags As Long
    strFilter = ahtAddFilterItem(strFilter, "Access Files (*.mda, *.mdb)", _
                    "*.MDA;*.MDB")
    strFilter = ahtAddFilterItem(strFilter, "dBASE Files (*.dbf)", "*.DBF")
    strFilter = ahtAddFilterItem(strFilter, "Comma Delimit Files (*.csv)", "*.csv")
    strFilter = ahtAddFilterItem(strFilter, "Excel Files (*.xls)", "*.xls")
    strFilter = ahtAddFilterItem(strFilter, "Text Files (*.txt)", "*.txt")
    strFilter = ahtAddFilterItem(strFilter, "All Files (*.*)", "*.*")

    ' Uncomment this line to try the example
    ' allowing multiple file names:
    ' lngFlags = ahtOFN_ALLOWMULTISELECT Or ahtOFN_EXPLORER

    Dim result As Variant

    result = ahtCommonFileOpenSave(InitialDir:=CurrentProject.path, _
        filter:=strFilter, FilterIndex:=4, Flags:=lngFlags, OpenFile:=False, _
        filename:="", DialogTitle:="Import Receive Data")
'** ตั้งค่า option OpenFile:= False จะได้ Save as dialog ถ้า OpenFile:= True >> Open dialog ซึ่งกรณีนี้เลือก False ครับ

    If lngFlags And ahtOFN_ALLOWMULTISELECT Then 'ตรงนี้เข้าใจว่าตรวจสอบว่าได้ลือกไฟล์หรือไม่ครับ
    Else 'Choose file
       ExportFile= result
    End If

    ' Since you passed in a variable for lngFlags,
    ' the function places the output flags value in the variable.
    Debug.Print Hex(lngFlags)
End Function



การใช้งานและการ Export เป็นไฟล์ Excel จาก Query

private sub EventXXX()
Dim pathfile As String
Dim fname As String

pathfile = ExportFile 'เรียกใช้งาน Dialog แล้วเก็บค่าพาธที่ได้มาใช้งาน
If pathfile = "" Then
Else

'ส่วนของการ Export จาก Query (ของผมเป็นการ Export จาก Query ที่ใช้ Criteria เพิ่มเนื่องจากในหน้าจอมีการปรับเปลี่ยน Filter ได้ตลอด และต้องการให้ Export ตามที่ Filter

Dim qdf As DAO.QueryDef, dbs As DAO.Database

Set dbs = CurrentDb
Set qdf = dbs.CreateQueryDef("ExportQuery", "SELECT * FROM [Query or Table] where xxxx") 'xxxx คือ Criteria ที่ต้องการให้ Export ออกมา

'คำสั่งนี้เป็นคำสั่ง Export เป็น Excel ครับ (ExportQuery คือชื่อ Query ที่ตั้งไว้ด้านบน) , (pathfile คือ ไฟล์จาก function open Dialog ที่สร้างไว้)

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "ExportQuery", pathfile, True, "Receive Data"

MsgBox "Export Complete!", vbInformation
qdf.Close

End If

5 @R20414
เพิ่มเติมครับ

ส่วนที่สร้าง Open/Save Dialog นั้น เอาไว้ใน form จะดีกว่าครับถ้ามีการใช้ Dialog หลายแบบ แต่ถ้าใช้แบบเดียวทำเป็น public function ได้ครับ

ส่วนเรื่อง Export แบบ 1 file excel หลาย Sheet เหมือนที่ อ.สันติสุข บอกเลยครับ
ตัวอย่าง

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table or QueryName", _
pathfile, True, "SheetName1"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table or QueryName", _
pathfile, True, "SheetName2"

6 @R20415
อีกครั้งครับ ที่ผมโพสก่อนหน้าเป็นแบบเดียวกับที่ อ.สันติสุขบอกตามลิ๊งค์นี้ครับ ผมไม่ทันได้อ่าน

- ถ้าจะเอาโค้ดที่ไม่ต้องเพิ่ม Object Library ที่ว่าไว้
http://www.thai-access.com/yeadram_view.php?topic_id=381

ขอโทษอีกครั้งครับ
7 @R20423
ขอบคุณคุณTIDE และทุกท่านมากครับ
ผมมือมือน่ะครับเรื่องการใช้ Code
รบกวนช่วยอธิบายเพิ่มเติมว่า Code ไหน ใส่ปุ่มไหนยังไงบ้างน่ะครับ
ขอบคุณครับผม
8 @R20425
ขอบคุณคุณTIDE และทุกท่านมากครับ
ผมมือมือน่ะครับเรื่องการใช้ Code
รบกวนช่วยอธิบายเพิ่มเติมว่า Code ไหน ใส่ปุ่มไหนยังไงบ้างน่ะครับ
ขอบคุณครับผม
9 @R20455
โค้ดด้านบนแบ่งเป็น 3 ส่วนครับ

โค๊ดส่วนแรก (ตั้งแต่ '***************** Code Start **************)
    เป็นส่วนที่สร้าง Dialog box ที่ใช้เปิดโฟลเดอร์หาไฟล์ ให้เอาไว้ที่ Module ครับ (สร้าง module ชืออะไรก็ได้แล้ววางโค๊ดส่วนแรกได้เลยครับ)
*ส่วนนี้จะเป็น Function เอาไว้เรียกใช้ครับ ไม่ได้ใส่ใว้ภายใน event ของปุ่มกด

โค๊ดส่วนที่ 2 (ตั้งแต่ 'open dialog for Export)
   เป็นส่วนที่กำหนดว่า Dialog box ที่จะใช้มีรายละเอียดแบบไหน ให้เอาโค๊ดส่วนนี้ไว้ที่ ฟอร์มที่ต้องการเรียกใช้ครับ
*ส่วนนี้จะเป็น Function เอาไว้เรียกใช้ครับ ไม่ได้ใส่ใว้ภายใน event ของปุ่มกด

โค๊กส่วนที่ 3 ()
   เป็นส่วนที่เอาไว้เรียกใช้งานการ Export file ครับซึ่งส่วนนี้จะเป็นส่วนที่อยู่ใน Event กดปุ่มที่จะใช้เป็นปุ่ม Export ครับ เมื่อกดปุ่มคำสั่งจะทำการเรียกใช้งาน Function ที่ได้วางไว้ก่อนหน้าให้เรียก Dialog box ขึ้นมาเมื่อเลือกไฟล์ได้แล้วจะได้ข้อมูลกลับมาเป็นพาธไฟล์ครับ (เช่น C:\Program Files\ )

10 @R20458
ขอบคุณ คุณ TIDE ครับผม
11 @R24112
รบกวนสอบถามนะคะ ตอนนี้กำลังติดปัญหา ในเรื่อง export ออกมาเป็น excel ค่ะ แต่ก็มือใหม่มากๆ ไม่รู้จะเริ่มตรงไหนก่อน ขอความรู้ตั้งแต่เริ่มได้ไหมค่ะ รบกวนอธิบายแบบเข้าใจง่ายๆคะ
@ ประกาศใช้งานเว็บบอร์ดใหม่ => บอร์ดเรียนรู้ Access สำหรับคนไทย
แล้วจะใส่ลิ้งอ้างอิงมาที่โพสต์เก่านี้หรือไม่ก็ตามสะดวกครับ
Time: 0.3205s