1

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

  1. 但它非常慢 - 让我的电脑在运行的 1-2 分钟内没有响应。
  2. 这些文件大约有 14,000 kb - 所以不会太大。

如果可能的话,我希望有人告诉我我可以做些什么来让它运行而不会导致我的计算机挂起。提前致谢。

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
4

2 回答 2

3

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

进行的优化

  1. 避免单元格范围循环,尤其是逐个单元格地编写。请改用数组。这是最大的
  2. Resize(1,1)什么都不做,因为它将单元格保持为单个单元格
  3. LongInteger
  4. 使用字符串函数Mid$而不是它们较慢的变体替代方案Mid
  5. allread变量是不必要的中间步骤
  6. 使用对象的变量名(即ws工作表),防止更长的引用

代码

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
于 2013-03-07T22:37:38.357 回答
0

您可以尝试在更新单元格时关闭屏幕更新。如果您要触摸大量单元格,这肯定会加快速度。

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

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

于 2013-03-07T19:46:38.760 回答