我有一些代码读取制表符分隔文件,其中单元格引用B2与制表符分隔文件中第一列中的引用匹配。这在文本文件很小的情况下工作正常。以下内容适用于带有ab和cc作为带有虚拟数据的标题的示例文件。
Option Explicit
Sub TestImport() 调用ImportTextFile(Sheet1.Range(" B1"),vbTab,Sheet2.Range(" A4")) 结束子
Public Sub ImportTextFile(strFileName As String,strSeparator As String,rngTgt As Range) Dim lngTgtRow As Long Dim lngTgtCol As Long Dim varTemp As Variant Dim strWholeLine As String Dim intPos As Integer Dim intNextPos As Integer Dim intTgtColIndex As Integer
Dim wks As Worksheet
Set wks = rngTgt.Parent
intTgtColIndex = rngTgt.Column
lngTgtRow = rngTgt.Row
Open strFileName For Input Access Read As #1
While Not EOF(1)
Line Input #1, strWholeLine
varTemp = Split(strWholeLine, strSeparator)
If CStr(varTemp(0)) = CStr(Range("B2")) Then
wks.Cells(lngTgtRow, intTgtColIndex).Resize(, UBound(varTemp) + 1).Value = varTemp
lngTgtRow = lngTgtRow + 1
End If
Wend
Close #1
Set wks = Nothing
End Sub
我正在尝试使用ADO使用下面的代码来运行,因为这将在具有几百万条记录的文本文件上运行得更快但是我在' .Open str&#39上收到错误;部分代码(没有给出一个或多个必需参数的值)。
看起来它与我如何定义字符串有关 - 你能查看一下我是否有遗漏的东西......?
Sub QueryTextFile()
t = Timer
Dim cnn As Object
Dim str As String
Set cnn = CreateObject("ADODB.Connection")
cnn.Provider = "Microsoft.Jet.OLEDB.4.0"
cnn.ConnectionString = "Data Source=C:\Users\Davids Laptop\Documents\Other Ad Hoc\Test Files\;Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
cnn.Open
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
str = "SELECT * FROM [test1.txt] WHERE [aa]=" & Chr(34) & Range("B2") & Chr(34)
With rs
.ActiveConnection = cnn
.Open str
Sheet1.Range("A4").CopyFromRecordset rs
.Close
End With
cnn.Close
MsgBox Timer - t
End Sub