将文本文本从文本文件粘贴到工作表中

我有以下代码从文本文件粘贴到我的工作表中的文本。 问题是这一切都在一线!

例如,如果文本文件如下所示:

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. 

我宁愿把它一行一行地写下来,这样:

 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 

你可以简单地打印循环中的每一行。

 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而不是旧的代码风格。

尝试下面的代码,可以将每行(从文本文件)保存到数组元素,然后循环遍历所有数组元素,并在列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