Excel VBA Extract Specific Start和;文本文件的长度

时间:2013-03-07 19:42:02

标签: arrays excel excel-vba vba

我有一个Excel 2007的代码,运行没有失败。

  1. 但它非常&异常缓慢 - 使我的计算机在运行的1-2分钟内没有响应。
  2. 文件大约是14,000 kb - 所以不要太大。
  3. 如果可能的话,我希望有人告诉我,我可以做些什么来让它运行而不会导致计算机挂起。提前谢谢。

    Sub ReadFileIntoExcel()
    
    Dim fPath As String
    Const fsoForReading = 1
    Dim readlength As Integer
    Dim readstart As Integer
    readlength = Worksheets("READFILE").Cells(1, "E").Value
    readstart = Worksheets("READFILE").Cells(1, "D").Value
    fPath = Worksheets("READFILE").Cells(1, "C").Value
    
    Dim objFSO As Object
    Dim objTextStream As Object, txt, allread, rw
    
    
    Set objFSO = CreateObject("scripting.filesystemobject")
    If objFSO.FileExists(fPath) Then
    Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
    rw = 1
    
    Do Until objTextStream.AtEndOfStream
        txt = objTextStream.ReadLine
        allread = Trim(Mid(txt, readstart, readlength))
        With ActiveWorkbook.Sheets("READFILE").Cells(rw, 7).Resize(1, 1)
            .NumberFormat = "@" 'format cells as text
            .Value = Array(allread)
        End With
        rw = rw + 1
    Loop
    
    objTextStream.Close
    Set objTextStream = Nothing
    Set objFSO = Nothing
    Exit Sub
    

2 个答案:

答案 0 :(得分:3)

我更新了你的代码以使用数组,而不是逐个单元格编写并立即运行

进行了优化

  1. 避免细胞范围循环,尤其是细胞逐个细胞。请改用数组。这是最重要的一个
  2. Resize(1,1)不执行任何操作,因为它将单元格保持为单个单元格
  3. LongInteger
  4. 更有效率
  5. 使用字符串函数Mid$而不是较慢的变体替代Mid
  6. allread变量是一个不必要的中间步骤
  7. 使用对象的变量名称(即工作表的ws),可以防止更长的引用
  8. <强>码

    Sub ReadFileIntoExcel()
    
    Dim fPath As String
    Dim ws As Worksheet
    Const fsoForReading = 1
    Dim readlength As Long
    Dim readstart As Long
    Dim rw as Long
    Dim X()
    
    Set ws = Worksheets("READFILE")
    readlength = ws.Cells(1, "E").Value
    readstart = ws.Cells(1, "D").Value
    fPath = ws.Cells(1, "C").Value
    
    Dim objFSO As Object
    Dim objTextStream As Object
    
    
    Set objFSO = CreateObject("scripting.filesystemobject")
    If objFSO.FileExists(fPath) Then
    Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
    rw = 1
    
    ReDim X(1 To 1, 1 To 1000)
    
    Do Until objTextStream.AtEndOfStream
        txt = objTextStream.ReadLine
        If rw Mod 1000 = 0 Then ReDim Preserve X(1 To 1, 1 To UBound(X, 2) + 1000)
        X(1, rw) = Trim$(Mid$(txt, readstart, readlength))
        rw = rw + 1
    Loop
    
    ws.[G1].Resize(UBound(X, 2), 1) = Application.Transpose(X)
    ws.Columns("G").NumberFormat = "@"
    
    objTextStream.Close
    Set objTextStream = Nothing
    Set objFSO = Nothing
    Exit Sub
    End If
    End Sub
    

答案 1 :(得分:0)

您可能会尝试在更新单元格时关闭屏幕更新。如果你触摸了很多细胞,这肯定会加快速度。

Application.ScreenUpdating = False
...update cells...
Application.ScreenUpdating = True

您还可以执行其他操作,例如关闭计算,但听起来您没有公式尝试评估设置的单元格。