将文本文件导入Excel VBA空行新列

时间:2015-03-20 18:39:09

标签: excel vba excel-vba

我在txt文件中有单列数据。我需要导入Excel并将每个字段分成空行的新列。我不确定在导入时是否最好这样做,或者在导入后执行此操作。

Foobar
detail1
detail2
val1
val2
val3
val4
randominfo

Widget
detail1
detail2
val1
val2
val3
val4
randominfo

1 个答案:

答案 0 :(得分:3)

您需要逐行读取文件,并在读取空行时移动。

编辑:忘记回答你的问题...只需在导入时执行即可。另一种方法是让您再次扫描列表并且效率不高。

Dim r As Integer
Dim c As Integer

''Initialize
r = 2
c = 1

''I'm assuming you have row headers or something so row starts at two.
''change to 1 if you want the data to be in the first row.

Open [your file path here] For Input As #1
Do Until EOF(1)
     Line Input #1, readLine
     If readLine = "" Then
        'Index over one column
        'Start row indexer over
        c = c + 1
        r = 2

     Else
        'Output "readLine" to the sheet
        ActiveSheet.Cells(r, c).Value = readLine
        'Index down one row
        r = r + 1
     End If


Loop

Close #1
相关问题