Page 1 of 1

ดึงข้อมูลในรูปแบบ text ด้วย VB แล้วมีปัญหา

Posted: Tue Oct 04, 2011 9:36 pm
by tigerwit
ตามไฟล์ที่แนบมาครับ
Sheet Gra1 เขียนโค๊ด VB ใส่ปุ่มนำเข้าข้อมูลแล้วมีปัญหาดังนี้ครับ
ถ้าเลือกไฟล์ .txt ตัวใดแล้วคลิก เปิด จะสามารถนำเข้าได้
แต่ถ้าเลือกไฟล์ .txt ตัวใดแล้วคลิก ยกเลิก จะ Run-time Error 1004


code VB (อาจารย์ให้คำแนะนำนานแล้ว)
Sub Import()
Dim rTarget As Range
Dim TextFileImport As String
TextFileImport = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
"Select Text Data File")
Set rTarget = Worksheets("Gra1").Range("A2").End(xlUp).Offset(1, 0)
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & TextFileImport, _
Destination:=rTarget)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 874
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub

Re: ดึงข้อมูลในรูปแบบ text ด้วย VB แล้วมีปัญหา

Posted: Tue Oct 04, 2011 10:06 pm
by snasui
:D ลองแทรก If เข้าไปช่วยครับ

Code: Select all

Sub Import()
Dim rTarget As Range
Dim TextFileImport As String
TextFileImport = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
"Select Text Data File")
If TextFileImport = "False" Then
    MsgBox "Please select file for import."
    Exit Sub
End If
Set rTarget = Worksheets("Gra1").Range("A2")
'Other code
End Sub

Re: ดึงข้อมูลในรูปแบบ text ด้วย VB แล้วมีปัญหา

Posted: Thu Oct 20, 2011 2:36 pm
by bank9597
จะนำไปประยุกต์อีกครับ