Page 1 of 1

ผมใช้ VBA นำเข้า text file เข้า excel แล้ว เลขศูนย์นำหน้าหายไป ต้องแก้ไขอย่างไรครับ

Posted: Wed Nov 18, 2020 12:51 pm
by 9KiTTi
หลังจากที่ผมขอคำปรึกษาเรื่องการนำไฟล์ txt เข้า excel โดยใช้ VBA ได้แล้ว แต่หลังจากที่นำเข้าได้แล้ว พบว่ามีปัญหาในบางคอลัมม์ตัวเลขศูนย์หายไป รบกวนแนะนำวิธีแก้ไขโดยใช้ VBA ด้วยครับ

Code: Select all

Sub ImportTXTFiles()
    Dim fso As Object
    Dim xlsheet As Worksheet
    Dim qt As QueryTable
    Dim txtfilesToOpen As Variant, txtfile As Variant
    On Error Resume Next
    
    Application.ScreenUpdating = False
    Set fso = CreateObject("Scripting.FileSystemObject")

    txtfilesToOpen = Application.GetOpenFilename _
                 (FileFilter:="Text Files (*.txt), *.txt", _
                  MultiSelect:=True, Title:="Text Files to Open")
    If VarType(txtfilesToOpen) = vbBoolean Then
        MsgBox "Please select file."
        Exit Sub
    End If

    For Each txtfile In txtfilesToOpen
        ' FINDS EXISTING WORKSHEET
        For Each xlsheet In ThisWorkbook.Worksheets
            If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
                xlsheet.Activate
                GoTo ImportData
            End If
        Next xlsheet

        ' CREATES NEW WORKSHEET IF NOT FOUND
        Set xlsheet = ThisWorkbook.Worksheets.Add( _
                             After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
        xlsheet.Activate
        GoTo ImportData

ImportData:
        ' DELETE EXISTING DATA
        ActiveSheet.Range("A:Z").EntireColumn.Delete xlShiftToLeft

        ' IMPORT DATA FROM TEXT FILE
        With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & txtfile, _
          Destination:=ActiveSheet.Cells(1, 1))
            .TextFileParseType = xlDelimited
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFilePlatform = 65001
            .TextFileOtherDelimiter = "|"

            .Refresh BackgroundQuery:=False
        End With

    ActiveSheet.Range("A1").AutoFilter Field:=1, Visibledropdown:=True
    ActiveSheet.Range("A1").AutoFilter Field:=2, Visibledropdown:=True

       Cells.Select
        Selection.NumberFormat = "0"
    
        For Each qt In ActiveSheet.QueryTables
            qt.Delete
        Next qt
    Next txtfile

    Application.ScreenUpdating = True
    MsgBox "นำข้อมูลสำเร็จแล้ว", vbInformation, "สำเร็จแล้ว"

    Set fso = Nothing
End Sub
รบกวนแนะนำด้วยครับ ขอบพระคุณครับ

Re: ผมใช้ VBA นำเข้า text file เข้า excel แล้ว เลขศูนย์นำหน้าหายไป ต้องแก้ไขอย่างไรครับ

Posted: Thu Nov 19, 2020 8:51 am
by 9KiTTi
ผมหาทางแก้ไขได้เรียบร้อยแล้วครับ