使用VBA高效读取txt文件(或其他数据源)

时间:2014-09-15 08:46:55

标签: excel excel-vba import vba

我有一个(大)数据列存储在txt文件中。 我需要在Excel工作表中复制列向量。这是我的代码:

Dim t As Single
t = Timer

Dim sFile As String
inputFile = "C:\Temp\vector.txt"

Dim rowNum As Long
rowNum = 1
Dim dest As Range
Set dest = Sheet1.Cells(rowNum, 1)

Open inputFile For Input As #1
Do Until EOF(1)
    Input #1, ReadData
    If Not IsEmpty(ReadData) Then
        dest.Cells = ReadData
        rowNum = rowNum + 1
        Set dest = Sheet1.Cells(rowNum, 1)
    End If
Loop
Close #1 'close the opened file

Sheet1.[C2].Value = Timer - t

我想知道是否有更有效/快速的方法来完成同样的任务。 为此目的,将txt文件转换为另一种格式(比如.csv,.xlsx或任何其他文件类型)而不是从.txt文件中读取行是否有意义? 任何帮助都非常感谢。 小号

2 个答案:

答案 0 :(得分:0)

关注this link我尝试了不同的解决方案。 与初始问题中提出的代码相比,以下代码提供了更快的问题解决方案(在Excel中导入500,000个随机数的列)。

Dim t As Single
t = Timer

Dim inputFile As String
inputFile = "C:\Temp\vector.txt"

Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1")

Set wbO = Workbooks.Open(inputFile)

wbO.Sheets(1).Columns(1).Copy wsI.Columns(1)
wbO.Close SaveChanges:=False

Sheet1.[C2].Value = Timer - t

特别是,在20次试验后,平均计算时间为1.50秒,而第一个代码则为10.2秒。 希望这有帮助!

答案 1 :(得分:0)

如果您想使用第一种方法(我推荐它,因为它不涉及通过Excel打开文件),那么您可以通过批量打印来减少运行时间。 您也可以考虑使用scripting.filesystemobject而不是旧的IO接口。

参见下面的示例(注意此代码尚未经过测试)

const path as string = ""
const max_print_rows as integer = 10000

dim print_start_cell as range
dim print_arr () as string
dim i as integer,j as long
dim fso as scripting.filesystemobject
dim in_file as scripting.textstream

set print_start_cell=thisworkbook.names("Start_Cell").referstorange
set fso=new scripting.filesystemobject
set in_file=fso.opentextfile(path,forreading)

redim print_arr(1 to max_print_rows,1 to 1)

do until in_file.atendofstream
  i=i+1

  print_arr(i)=in_file.readline

  if I=max_print_rows then
    print_start_cell.offset(j).resize(max_print_rows).value=print_arr
    j=j+i
    erase print_arr
    redim print_arr(1 to max_print_rows)
    i=1
  end if

loop

print_start_cell.offset(j).resize(max_print_rows).value=print_arr
erase print_arr

in_file.close
set in_file=nothing

set print_start_cell=nothing
set fso=nothing