我们正在开展一项工作,需要将数据从分隔的文本文件插入到Excel工作表中。代码已准备就绪并且正常工作,但它逐个单元地插入数据,使其成为一个非常缓慢的过程。请建议一种方法将数据一次性插入整个范围,这样可以使操作更快。
找到下面的代码段。
Open FName For Input Access Read As #1
While Not EOF(1)
Line Input #1, WholeLine
If Right(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
ColNdx = SaveColNdx
Pos = 1
NextPos = InStr(Pos, WholeLine, Sep)
While NextPos >= 1
TempVal = Mid(WholeLine, Pos, NextPos - Pos)
Cells(RowNdx, ColNdx).Value = TempVal
Pos = NextPos + 1
ColNdx = ColNdx + 1
NextPos = InStr(Pos, WholeLine, Sep)
Wend
RowNdx = RowNdx + 1
Wend
答案 0 :(得分:1)
您可以尝试在Excel中打开分隔文件作为csv / txt文件:这很快。
或者您可以按单元格创建并填充二维变体数组,然后将变量数组分配给Excel范围。这将更快,因为它最小化了对象模型开销。
答案 1 :(得分:1)
为什么不能像在Excel中一样打开csv文件(或变体)
下面的代码将每一行作为变量数组导入,然后逐行转储到Excel。在将数据输入Excel之前,我可能应该更进一步并将每个行数组转储到单个组合数组中,但我这样做是因为我不清楚为什么忽略单个整体输入
另外,我认为这些行是多余的,因为它只是在最右边的单元格中添加一个空白的“记录”。
If Right(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
主要代码
Sub Test()
Dim fName As String
Dim Sep As String
Dim WholeLine As String
Dim lngCnt As Long
Dim aRRSplit()
fName = "c:\test.csv"
Sep = ","
Open fName For Input Access Read As #1
While Not EOF(1)
Line Input #1, WholeLine
If Right$(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
aRRSplit = Application.Transpose(Split(WholeLine, Sep))
lngCnt = lngCnt + 1
Cells(lngCnt, 1).Resize(1, UBound(aRRSplit)) = Application.Transpose(aRRSplit)
Wend
Close #1
End Sub
答案 2 :(得分:0)
以下是我在网上找到的一些代码,它对我很快起作用。
Function doFileQuery(fileName As String, outSheet As String) As Boolean
Dim rootDir As String
rootDir = "W:\Development"
Dim connectionName As String
connectionName = "TEXT;" + rootDir + "\" + fileName
With Worksheets(outSheet).QueryTables.Add(Connection:=connectionName, Destination:=Worksheets(outSheet).Range("A5"))
.Name = fileName
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.Refresh BackgroundQuery:=False
End With
doFileQuery = True
End Function
希望这有帮助!