将文本文件中的文本逐行粘贴到工作表中

时间:2017-02-26 10:50:33

标签: excel vba excel-vba text

我有以下代码将文本文件中的文本粘贴到我的工作表中。问题是它把它全部放在一条线上!

例如,如果文本文件为:

Opened by Joe Bloggs 24 Feb 2017 11:08:12
Closed by Joe Bloggs 24 Feb 2017 11:23:12

这将全部粘贴到Range(“A1”)中:

Opened by Joe Bloggs 24 Feb 2017 11:08:12 Closed by Joe Bloggs 24 Feb 2017 11:23:12.

我希望它是逐行粘贴在A列上的,这样:

Range("A1").Value = Opened by Joe Bloggs 24 Feb 2017 11:08:12
Range("A2").Value = Closed by Joe Bloggs 24 Feb 2017 11:23:12

我的代码

Private Sub CommandButton1_Click()

Dim myFile As String, text As String, textline As String, Delimiter As String

myFile = "J:\...\Group Jobslist V1.2. Log.Log"

Open myFile For Input As #1
Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
Loop
Close #1
Range("A1").Value = text

End Sub

2 个答案:

答案 0 :(得分:1)

您只需在循环中打印每一行。

Private Sub CommandButton1_Click()

    Dim myFile As String, textline As String
    myFile = "J:\...\Group Jobslist V1.2. Log.Log"

    Dim i As Long
    Open myFile For Input As #1
    Do Until EOF(1)
        i = i + 1
        Line Input #1, textline
        Range("A" & i).Value = textline
    Loop
    Close #1

End Sub

您也可以使用FileSystemObject而不是旧代码样式。

答案 1 :(得分:0)

尝试下面的代码,您可以将每一行(从文本文件)保存到数组元素,然后循环遍历所有数组元素并在列A中逐行打印。

Option Explicit

Private Sub CommandButton1_Click()

Dim myFile As String, text As String, textline() As Variant, Delimiter As String
Dim i As Long

myFile = "J:\...\Group Jobslist V1.2. Log.Log"
ReDim textline(1 To 1000) '<-- Init array to large size

i = 1
Open myFile For Input As #1
Do Until EOF(1)
    Line Input #1, textline(i)
    text = text & textline(i)
    i = i + 1
Loop
Close #1

ReDim Preserve textline(1 To i - 1) '<-- resize array to number of lines

' loop through all array elements and print each one in column A (new row)
For i = 1 To UBound(textline)
    Range("A" & i).Value = textline(i)
Next i

End Sub