การเลือก import ไฟล์
กระทู้เก่าบอร์ด อ.Yeadram

 16,680   22
URL.หัวข้อ / URL
การเลือก import ไฟล์


ปรกติ สำหรับ access ในการนำไฟล์พวก TXT หรือ excel มันต้องกำหนดชื่อไฟล์และpath ที่แน่นอนใน Macro พวก Transfertext หรือTransferSpreadsheet แล้วถึงimport เข้าไปใน tableได้

ไม่ทราบว่ามีวิธีให้ User เลือก Brows ไฟล์เองได้ใหมครับ

หรือpopup ขึ้นมาให้พิมพ์ชื่อไฟล์ก็ยังดีครับ

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

1 @R01639
Private Sub cmd_Browse_Click()
Dim s As String

    If IsNull(txt_FilePath) Or txt_FilePath = "" Then
        s = GetOpenFile("D:\")
    Else
        s = GetOpenFile(Me.txt_FilePath)
    End If
    If s = "" Then
        'MsgBox "Nothing was selected"
    Else
        If Dir(s) = "" Then
            Beep
            MsgBox "ไม่พบไฟล์ " & s
        Else
            'If MsgBox("Do you want to overwrite the file '" & s & "'?", vbYesNoCancel) = vbYes Then
            '    เสียง = s
            'Else
            'End If
            txt_FilePath = s
        End If
    End If
End Sub

----------- Modules--------------------------------------
Option Compare Database
Option Explicit

'***************** 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 courtesy of:
'   Microsoft Access 95 How-To
' Ken Getz and Paul Litwin
' Waite Group Press, 1996

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 GetOpenFile(Optional varDirectory As Variant, Optional varTitleForDialog As Variant) As Variant
' Here's an example that gets an Access database name.
Dim strFilter As String
Dim lngFlags As Long
Dim varFileName As Variant
' Specify that the chosen file must already exist,
' don't change directories when you're done
' Also, don't bother displaying
' the read-only box. It'll only confuse people.
    lngFlags = ahtOFN_FILEMUSTEXIST Or ahtOFN_HIDEREADONLY Or ahtOFN_NOCHANGEDIR
    If IsMissing(varDirectory) Then
        varDirectory = ""
    End If
    If IsMissing(varTitleForDialog) Then
        varTitleForDialog = "Please choose a Target File ..."
    End If

    ' Define the filter string and allocate space in the "c"
    ' string Duplicate this line with changes as necessary for
    ' more file templates.
    strFilter = ahtAddFilterItem(strFilter, "All File (*.*)", "*.*")               '   "Access (*.mdb)", "*.MDB")
    ' Now actually call to get the file name.
    varFileName = ahtCommonFileOpenSave(OpenFile:=True, InitialDir:=varDirectory, Filter:=strFilter, flags:=lngFlags, _
                    DialogTitle:=varTitleForDialog)
    If Not IsNull(varFileName) Then
        varFileName = TrimNull(varFileName)
    End If
    GetOpenFile = varFileName
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
'************** Code End *****************

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
        ahtCommonFileOpenSave = TrimNull(OFN.strFile)
    Else
        ahtCommonFileOpenSave = vbNullString
    End If
End Function

ผมใช้อยู่
2 @R01640
ขอบคุณครับ แต่บังเอิญผมเป็นมือใหม่น่ะครับ ต้องขอรบกวนให้บอกละเอียดนิดนึงครับ

ช่วยอธิบายนิดนึง นำโค้ดที่ว่าไปใส่ตรงใหน

แล้ว copy ข้างบน ทั้งหมดเลยหรือเปล่าครับ


ขอบคุณครับ
3 @R01641
1. ให้สร้างโมดูลขึ้นมา 1 โมดูล แล้ว copy code ตั้งแต่ที่มีคำว่า Option Compare Database ซึ่งอยู่ใต้บรรทัด ----------- Modules------------- ไปจนถึงท้ายสุดที่คำว่า End Function   วางในโมดูลที่สร้างขึ้นมา แล้ว save เป็นชื่อโมดูลอะไรก็ได้
2.สร้างฟอร์มใหม่ 1 ฟอร์ม save ชื่อฟอร์มอะไรก็ได้
3.สร้างกล่องข้อความ( text box) 1 อัน ตั้งชื่อว่า txt_FilePath
4.สร้างปุ่มคำสั่ง(command botton) 1 อัน ตั้งชื่อว่า cmd_Browse
5.คลิ๊กเม้าส์ขวาที่ปุ่มคำสั่ง cmd_Browse แล้วเลือก สร้างเหตุการณ์ เพื่อเปิด form class module ขึ้นมา
6.copy code ตั้งแต่
Private Sub cmd_Browse_Click()
Dim s As String

    If IsNull(txt_FilePath) Or txt_FilePath = "" Then
        s = GetOpenFile("D:\")
    Else
        s = GetOpenFile(Me.txt_FilePath)
    End If
    If s = "" Then
        'MsgBox "Nothing was selected"
    Else
        If Dir(s) = "" Then
            Beep
            MsgBox "ไม่พบไฟล์ " & s
        Else
            'If MsgBox("Do you want to overwrite the file '" & s & "'?", vbYesNoCancel) = vbYes Then
            '    เสียง = s
            'Else
            'End If
            txt_FilePath = s
        End If
    End If
End Sub

ลงไปใน form class module แล้วบันทึกฟอร์ม

7.ลองเปิดฟอร์ม แล้วคลิ๊กปุ่มลองดู

4 @R01642
ผมลองทำแล้ว ได้dialog มาตามที่บอกเลยครับ แต่ผมยังมีปัญหาอยู่


1. ได้มาแล้วจะเอาไปใช้งานยังไงในการที่จะเลือก import file นั้นเข้ามา

อย่างตอนนี้ผมใช้ macro TransferSpreadsheet อยู่ โดยสมมุติว่าให้ import เข้า table1   ต้องทำยังไงต่อให้โปรแกรมรู้ว่าต้องไปเอาpathของไฟล์จากcodeที่เราได้มาจาก ไฟล์ที่เราเลือกเปิดมาครับ

รบกวนนิดนึงนะครับ พอดีผมเป็นมือใหม่และยังไม่เคยเขียนโปรแกรมเลยน่ะครับ
5 @R01643
รูปตัวอย่างน่ะครับ ทำยังไงถึงจะเอาค่าตรง text box ชื่อtxt_FilePath

ไปเป็นค่าตรง file name ตรง macro ได้ หรือว่ามีวิธีอื่นก็ได้ครับ

6 @R01646
แมคโคร มันมีข้อจำกัด มันไม่ค่อยยืดหยุ่นกับการเขียนโค้ดเข้าช่วยงานครับ
งานเดียวกันนี้ คุณสามารถ ใช้ VBA ทำแทนแมคโครได้ครับ มันจะยืดหยุ่นกว่า

ลองเปิด VBA แล้วพิมพ์คำว่า TransferSpredsheet ทีนี้ select ทั้งคำ แล้วกด F1 มันจะเปิด help มาลองศึกษาดูการเขียนคำสั่งนี้ ผ่าน VBA ครับ


Function ExcelImport()
dim pth as string ' ประกาศตัวแปรไว้เก็บ ชื่อไฟล์ต้นทาง
pth=GetOpenFile    ' เรียกใช้ฟังก์ชั่นที่คุณ Gerald แนะนำมา เพื่อเปิดไดอล็อกหาไฟล์ เมื่อได้มาแล้วมันจะไปอยู่ในตัวแปร pth
' เอาตัวแปร pth ไปเป็นค่าในอาร์กิวเมนต์ ของคำสั่ง Transfer
Docmd.TransferSpreadsheet acImport, "Microsoft Excel 8-10",Table1,pth,True
' สังเกตไหมครับ ว่ามันคล้ายๆ กันกับแมคโครนั่นแหละครับ เพราะว่า แมคโครมันคือการประยุกต์คำสั่ง VBA ครับ
End Function

ที่นี้มาว่ากันเรื่องการเรียกใช้ ก่อนหน้านี้คุณเรียกใช้แมคโครยังไง เรียกจากตรงไหนครับ ให้เปลี่ยนไปเรียกใช้ ฟังก์ชั่น ExcelImport แทนครับ
หรือถ้าถนัดแมคโครจริงๆ ให้คุณใช้แมคโครตัวเดิมนี่แหละครับ เปลี่ยนคำสั่งจาก TransferSpredsheet ให้เป็นคำสั่ง RunCode
มันจะมี อาร์กิวเมนต์ให้ใส่แค่ 1 อาร์กิวเมนต์ ให้คุณเขียนว่า ExcelImport()
แต่วิธีนี้ มีข้อจำกัดนิดหนึ่ง คือ คุณต้องเอาฟังก์ชั่น ExcelImport ไปวางในโมดูล


7 @R01647
ขอบคุณคุณ เอก มากนะครับ

อยากให้เจ้าของกระทู้ลองหาหนังสือพวก Step by Step หรือ workshop และดาวน์โหลด ตัวอย่างไหล์มาลองศึกษา จะเข้าใจได้เร็วขึ้นครับ พวกฟังก์ชั่นสำเร็นรูปจำนวนมากมีให้ดาวน์โหลดในอินเทอร์เนท ลองดูครับ
8 @R01664
กระทู้นี้ได้ความรุ้มากคับ

ผมอยากทราบเพิ่มเติมว่า

ถ้าต้องการ import excel file
บาง Column ใน excel

Code VB จะเป็นประมาณไหนคับ

รบกวนผู้รู้ช่วยบอกที
9 @R01813
Private Sub Command1_Click()
Application.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "Table1", "C:Book1.xls", False, "A1:D8"
End Sub
10 @R08147
ผมใช้คำสั่ง FileDialog() มันจะมีปัญหากับ Drive ที่เป็น network
แต่พอใช้ Function ที่ คุณ Gerald ใช้ได้ดีเลยครับผม ขอบคุณครับ
11 @R13016
มัน Browse ได้ แล้วจะส่งเข้าตารางยังไงครับ
12 @R17917
งงเหมือนกันครับ ส่งเข้าไงครับ
13 @R20786
มีใครพอจะตอบได้หรือไม่ครับ ที่คุณPapaei

และคุณเก่ง ถามต่อครับ ว่าจะส่งเข้าตารางยังไงครับ

งงด้วยคนครับพอดีเห็นน่าสนใจดีครับ
14 @R20834
ตอน Browse มาจะได้ path ของไฟล์ที่เลือกมาครับ (เช่น C:\Folder\Filename.xls)

ส่วนการเอาข้อมูลเข้าจะเป็นคำสั่ง DoCmd.TransferSpreadsheet นี้ครับ

ตามที่คุณ JZ บอก

Application.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "Table1", "C:\Book1.xls", False, "A1:D8"

คำสั่งด้านบนเป็นการ import ไฟล์ Excel ชื่อไฟล์ Book1.xls อยู่ที่ไดรฟ์ C
เอาเข้า table ชื่อ Table1

รายละเอียดคำสั่ง TransferSpreadsheet เพิ่มเติมครับ

https://msdn.microsoft.com/en-us/library/office/ff844793.aspx

เราสามารถเปลี่ยนให้เอาไฟล์ที่ Browse เข้ามาได้ด้วยการเปลี่ยน   "C:\Book1.xls" ให้เป็น path ที่เราได้มา (txt_FilePath)

ลองปรับใช้นะครับ
15 @R21050
ขอบคุณครับ ขอโทษทีมาขอบคุณช้าไปหน่อย
ลองทำตามแล้วติด Error

Application.DoCmd.TransferSpreadsheet acImport, "Microsoft Excel 8-10", "IERP1", pth, True, "A1:K60"

pth ="C:\Book1.xls" 'ประกาศเป็น String

Error = Type Mismatch

และถ้าไม่กำหนดช่วง จะเอาทั้งหมด ตัด "A1:K60" ออกได้หรือไม่ครับ

ขอบคุณครับ
16 @R21051
เปลี่ยนเป็น Application.DoCmd.TransferSpreadsheet acImport, , "IERP1", pth, True, "A1:K60"

ควรมี help file ติดตั้งเอาไว้ เพื่อเปิดดู reference ของแต่ละคำสั่งว่ามันทำงานอะไร มีพารามิเตอร์อะไรบ้างนะครับ
17 @R21052
ขอบคุณอาจารย์ครับ
ได้แล้วครับ ทำตามอาจารย์เลย

ผมก็ลองเข้าไปดูที่
https://msdn.microsoft.com/en-us/library/office/ff844793.aspx

แต่ก็ไม่เข้าใจครับ และเข้ามาถามอาจารย์ต่อ ฮ่าๆๆ(เข้าใจยากนิดครับ)

ขอบคุณครับ
18 @R21060
เรียนอาจารย์สันติสุข ครับ
ติดปัญหา Error เวลาผมกด ยกเลิกการเลือกไฟร์ ครับ
Error 2522 "The Action Or methot requires ตรงบรรทัดที่อาจารย์แนะนำครับ


ผมต้องเพิ่ม Code ยังไงในเงื่อนไขครับ

Function ExcelImport()
Dim pth As String
pth = GetOpenFile
Application.DoCmd.TransferSpreadsheet acImport, , "IERP1", pth, True

End Function

ขอบคุณครับ
19 @R21061
ผมเข้าใจว่ามันไม่พบเหตุการเมื่อ pth ไม่มีค่าใช่ หรือเปล่าครับ

ก็เพิ่มเข้าไปในพังชั่น

If pth <> "" Then
Application.DoCmd.TransferSpreadsheet acImport, , "IERP1", pth, True
Else
MsgBox "คุณได้ยกเลิกการนำเข้าข้อมูล"
End If


ขอบคุณครับ
20 @R21062
เวลาเราสั่ง DoCmd ถ้าคำสั่งนั้นไม่สามารถทำงานได้ครบกระบวนความของคำสั่งนั้น ไม่ว่าจะเนื่องจากอะไรก็ตาม มันก็จะแสดง error อย่างที่ว่านี่แหล่ะครับ ดังนั้นให้แก้ไขเพิ่มเติมเป็น

On Error Resume Next
Application.DoCmd.TransferSpreadsheet acImport, , "IERP1", pth, True
If Err.Number = 2522 then
   MsgBox "คุณได้ยกเลิกการนำเข้าข้อมูล"
   ...
   ...
End If
On Error Goto 0 หรือ On Error Goto Error_Handling_Routine_อะไรที่คุณมีใน_procedure_นี้ก็ว่าไป

@ ประกาศใช้งานเว็บบอร์ดใหม่ => บอร์ดเรียนรู้ Access สำหรับคนไทย
แล้วจะใส่ลิ้งอ้างอิงมาที่โพสต์เก่านี้หรือไม่ก็ตามสะดวกครับ
Time: 0.2625s