【问题标题】:How to optimize the performance of data pulling from a very large text file in excel via VBA如何通过 VBA 优化从 excel 中非常大的文本文件中提取数据的性能
【发布时间】:2019-10-23 12:33:17
【问题描述】:

我想获取有关该值与一行中的关键单元格值的数据。 问题是文件真的很大,我有一个 .txt 文件,它有大约 54000 行和 14 列,因此文本文件本身是 20 mb,超过这个我需要得到 D 列的值反对F 列中的值。 F 列中的值是唯一的。

到目前为止,我一直尝试直接的方法从 .txt 文件中提取数据并将其复制到工作表中,然后运行循环以获取附加值。

但代码在等待 15 分钟后仍无法从 .txt 文件中提取数据。

  Do While bContinue = True
  outRow = 1

  sInputFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")
  If sInputFile = "False" Then
     bContinue = False
     Reset 'close any opened text file
     Exit Sub

  Else
     outCol = outCol + 2

     'process text file
     fNum = FreeFile
     Open sInputFile For Input As #fNum

     Do While Not EOF(fNum)
        outRow = outRow + 1
        Line Input #fNum, sInputRecord
        Sheets("Sheet1").Cells(outRow, outCol).Value = sInputRecord
     Loop
     Close #fNum

  End If
  Loop

  errHandler:
  Reset 
  End Sub

我预计这需要一些时间,但运行此代码需要很长时间,这会破坏使用宏的目的。 我只是询问是否有人有更好的方法来解决这个问题。

【问题讨论】:

  • 为什么不直接在 Excel 中打开文件?或者使用从文件中获取数据>>

标签: excel vba text-files import-table


【解决方案1】:

代码的第一部分丢失了,但我猜你声明了变量。如果没有,那可能会对性能有所帮助。

您也可以尝试在流程开始时关闭计算,然后在最后切换回来。

Application.Calculation = xlCalculationManual
'...
Application.Calculation = xlCalculationAutomatic

您是说您只需要文本中的第 4 列和第 6 列,但您将整行放入一个单元格中。

如果您真的只想将一行的这两个部分放入工作表中,您可能需要执行以下操作:

 With Sheets("Sheet1")
     Do While Not EOF(fNum)
        outRow = outRow + 1
        Line Input #fNum, sInputRecord
        .Cells(outRow, outCol).Value = Split(sInputRecord,";")(3)
        .Cells(outRow, outCol+1).Value = Split(sInputRecord,";")(5)
     Loop
 End With

将分号更改为 txt 文件中的分隔符。

【讨论】:

    【解决方案2】:

    请试试这个并反馈。

    Sub TryMe()
    
    Dim cN As ADODB.Connection '* Connection String
    Dim RS As ADODB.Recordset '* Record Set
    Dim sQuery As String '* Query String
    On Error GoTo ADO_ERROR
    
    cN = New ADODB.Connection
    cN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\temp\;Extended Properties=""text;HDR=Yes;FMT=Delimited(,)"";Persist Security Info=False"
    cN.ConnectionTimeout = cN.Open()
    
    RS = New ADODB.Recordset
    sQuery = "Select * From VBA.csv ORDER BY ID"
    RS.ActiveConnection = cN
    RS.Source = sQueryRS.Open()
    If RS.EOF <> True Then
        While RS.EOF = False
        Open "c:\temp\vba_sorted.csv" For Append As 1
        Print #1, RS.Fields(0) & "," & RS.Fields(1); RS.MoveNext()
        Close #1
    End If
    If Not RS Is Nothing Then RS = Nothing
    If Not cN Is Nothing Then cN = Nothing
    
    ADO_ERROR:
    If Err <> 0 Then
    Debug.Assert (Err = 0)
    
    MsgBox (Err.Description)
    Resume Next
    End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2014-11-29
      • 2021-06-01
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2017-03-20
      • 2020-05-28
      • 2018-04-24
      相关资源
      最近更新 更多