读取文本文件中的特定参数,并在VB中写入excel

问题描述 投票:-3回答:1

我有如下示例文本:

 text....
 text.....
 .....
Reference No:123
IMEI No:785220222
text.....
text.....
 .........
Reference No:456
IMEI No:45666666
text.....
text.....
 .........
I required to read only given parameters such as Reference No & IMEI No and write to excel in two separate columns I was using below script but it only giving 1st iteration only.... Please help for same. Thanks in advanced..
Private Sub CommandButton1_Click()

Dim myFile As String, text As String, textline As String, _
    posLat As Integer, posLong As Integer
Dim X As Integer, A As String, B As String

myFile = "C:\test\IMEI_Nilanka.txt"

Open myFile For Input As #1
Do Until EOF(1)
    Line Input #1, textline
    X = 1

    text = text & textline
    A = "A" & X
    B = "B" & X    
    X = X + 1
Loop
Close #1

posLat = InStr(text, "Reference No.")
posLong = InStr(text, "IMEI NO")

Range(A).Value = Mid(text, posLat + 30, 7)
Range(B).Value = Mid(text, posLong + 30, 20)

End Sub
excel vba
1个回答
0
投票

未经测试:

Private Sub CommandButton1_Click()

Dim myFile As String, text As String, textline As String, _
    posLat As Integer, posLong As Integer
Dim X As Long, rw as Range

myFile = "C:\test\IMEI_Nilanka.txt"
Set rw = ActiveSheet.Rows(1)

Open myFile For Input As #1
Do Until EOF(1)
    Line Input #1, textline

    if textline like "*Reference No.*" Then
        Set rw=rw.offset(1,0)
        rw.cells(1).value=trim(replace(textline,"Reference No.",""))
    end if
    if textline like "*IMEI NO*" then
        rw.cells(2).value=trim(replace(textline,"IMEI NO",""))
    end if

Loop
Close #1


End Sub
© www.soinside.com 2019 - 2024. All rights reserved.