Field names from second row of data
กระทู้เก่าบอร์ด อ.สุภาพ ไชยา

 230   1
URL.หัวข้อ / URL
Field names from second row of data

มีคนถามไว้ที่ 
http://www.utteraccess.com/forums/showflat.php?Cat=&Board=access_2000&Number=110320&page=0&view=collapsed&sb=5&o=7&fpart=1&vc=1&PHPSESSID= 
 
ดังนี้ครับ 
I am importing text files into Access. The field names in the text files are on the 2nd row, so, I can't use the 'use first row as headings' option in the wizard. So I end up opening the file in Access and having to manually delete row 1 and 2 of the data and then manually typing in the field names in the table design view. 
 
Is there a way to use the field names from the 2nd row of the data and put these as the field names in Access without having to do it all manually? Thanks.  
 
โอนไฟล์ที่เป็น Text เข้ามาใน Access แต่ว่าชื่อฟีลด์จะอยู่ที่บรรทัดที่ 2 จึงไม่สามารถที่จะโอนเข้ามาโดยระบุว่าให้ใช้บรรทัดแรกเป็นชื่อฟีลด์ได้ เมื่อโอนเข้ามาแล้ว ต้องตัด 2 ข้อมูลแรกออก แล้วเปลี่ยนชื่อฟีลด์ให้ถูกต้องอีกที ด้วยมือ ทำอย่างให้สามารถใช้บรรทัดที่ 2 เป็นชื่อฟีลด์ได้ 
 
ผมได้ลองคิดดู 2 วิธีที่วิ่งเข้ามา คือ  
1. ตัด 2 บรรทัดแรกออกก่อนที่จะนำเข้า หรือ 
2. นำเข้าเหมือนเดิม แต่มาสร้างตารางขึ้นมาใหม่อีกตารางหนึ่ง ใช้โค้ดโดยไปดึงชื่อฟีลด์จากข้อมูลที่ 2 ของตารางแรก แล้วค่อยนำข้อมูลตั้งแต่ลำดับที่ 3 เป็นต้นไป ไปใส่ในตารางที่สร้างขึ้นมาใหม่ 
 
ผมจึงลองทำแบบแรกได้ดังนี้ครับ 
 
Sub RemoveFirstLine() 
Dim strData As String, strSkip As String 
Dim strOldFile As String, strNewFile As String 
 
On Error GoTo Err_FileOpen 
 
strOldFile = "FieldNameOn2.txt" 
strNewFile = "FieldNameOn21.txt" 
 
Open strOldFile For Input As #1 
Open strNewFile For Output As #2 
     
strSkip = "Yes" 
Do While Not EOF(1) 
    Line Input #1, strData 
    ' Skip the first line 
    If strSkip = "Yes" Then 
        strSkip = "No" 
    Else 
        Print #2, strData 
    End If 
Loop 
 
Close #1 
Close #2 
 
' Delete old file 
Kill strOldFile 
' Rename the new file back to the old name 
Name strNewFile As strOldFile 
 
Exit_Sub: 
    Exit Sub 
 
Err_FileOpen: 
    If Err = 55 Then ' File already open 
        Close #1 
        Close #2 
    Else 
        MsgBox "Run-time error '" & Err & "':" & _ 
            vbCrLf & vbCrLf & Err.Description, vbOKOnly 
    End If 
    Resume Exit_Sub 
 
End Sub 
 
หลักการของโค้ดข้างบน จะใช้วิธีไปสร้างไฟล์ใหม่ โดยมันจะไม่นำเอาบรรทัดแรกไปเขียนในไฟล์ชั่วคราว 
แล้วทำการลบไฟล์เก่า จากนั้นก็เปลี่ยนชื่อไฟล์ชั่วคราวไปเป็นไฟล์เดิม 
 
ส่วนวิธีที่ 2 นั้น ลองทำดูนะครับ ผมว่ามันท้าทายดีนะ 
 
จะเห็นว่า ความคิดเกี่ยวกับหลักการหรือจินตนาการที่จะทำหรือแก้ปัญหา มีความสำคัญมากกว่าวิธีการเขียนโค้ด 
 
ท่านว่าจริงมั๊ย??? *** Edited by Supap Chaiya *** 30/4/2003 21:37:33

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

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