2017-06-08 1 views
2

エクセルシートに.txtファイルとして保存された電子メールからコピー情報を取得しようとしています。 私が実行している問題は、ライン入力機能でDoループを使用するときです。現在の行にないテキスト行から情報を取得できません。私は、デリミネーターを含む行をコピーするコードも好きです。また、より高速なファイルの内容をループよりも一度に配列にファイルからテキスト全体を読み、そして働くことですVBAライン入力を使用する場合、下の行からテキストを取得する方法は?

intFreefile = FreeFile 
Open ThisWorkbook.Path & "\temp567.txt" For Input As #intFreefile 
lngRecordsInEmail = 0 
Do Until EOF(intFreefile) 
    Line Input #intFreefile, strText 
    If InStr(1, strText, strDelimiter) > 0 Then 
     If InStrRev(1, strText, strDelimiter) = 1 Then 
     ' if last character in line = deliminator then 
     ' how do i get the text on 2 lines below? 

     Else 
     ws.Cells(lngRow, 1).Value = strText 
     End If 

     If blColourCell Then 
      ws.Cells(lngRow, 1).Interior.ColorIndex = 35 
     End If 
     strText2 = strText2 + 1 
     lngRow = lngRow + 1 
     lngTotalRecords = lngTotalRecords + 1 
     lngRecordsInEmail = lngRecordsInEmail + 1 
    End If 
Loop 
Close 
+0

その後、別の行を読み取るために、あなたの区切り文字を見つけた後、あなたのループ内のコードを追加する必要があります。必要に応じてループを作ります。 –

答えて

2

私のお気に入りの方法:

この

は、私が使用していたコードですアレイと一緒に。これにより、必要な2行からテキストを取得するコントロールが強化されます。

これはあなたの試みですか? (未テスト

Dim MyData As String, strData() As String 
Dim i As Long 

intFreefile = FreeFile 

'~~> Open file and read it on one go 
Open ThisWorkbook.Path & "\temp567.txt" For Binary As #intFreefile 
MyData = Space$(LOF(1)) 
Get #intFreefile, , MyData 
Close #intFreefile '<~~ Close the text file after reading from it 

'~~> This array has the entire contents from the text file 
strData() = Split(MyData, vbCrLf) 

For i = LBound(strData) To UBound(strData) 
    '~~> Last character in line = deliminator 
    If Right(strData(i), 1) = strDelimiter Then 
     Debug.Print strData(i) 
     Debug.Print strData(i + 1) 
     Debug.Print strData(i + 2) 
    '~~> Else if the deliminator is somewhere else 
    ElseIf InStr(1, strData(i), strDelimiter) Then 
     Debug.Print strData(i) 
    End If 
Next i 
+0

ファイル番号をハードコーディングしないことを強くお勧めします。ローカル変数を使用して、FreeFileに割り当てて、VBAがどのファイル番号を自由に使用できるかを判断できるようにします。 –

+0

@ Mat'sMug:良い点。私はそれを更新しました:) –

関連する問題