excel - 高效使用 For 循环

标签 excel vba

我有一个相当大的 excel 文件(想想 65,000+ 行)。
在 excel 文件中,只有两列对本练习很重要:CCNumber 和 FileFound (Col BC/BD)。
我正在尝试使用 for 循环遍历 65,000 + 行并将 CCNumber (ID) 与文件文件夹(30,000 个文件)进行比较,然后如果 id 匹配/未找到打印“可用”或“未找到”在 FileFound 列中 - 如下:

Sub LoopFiles
    Dim fileName As Variant, csheet As Variant
    fileName = Dir("Some\Directory\Here\*pdf")

    Dim CCNums As Range
    Set CCNums = Range("BC4:BC68512")
    
    Application.ScreenUpdating = False
    While fileName <> ""        
        ID = Left(fileName,6) 'id is a 6 digit numeric number, strip away everything else        
        For Each CCNum in CCNums        
            csheet = Left(CCNum, 6)
            if(ID = csheet) Then
                CCNum.Offset(0,1).Value = "Available"
            Else
                CCNum.Offset(0,1).Value = "Not Found"
            End If
        Next CCNum
        fileName = Dir
    Wend
    Application.ScreenUpdating = True
End Sub
以上是非常低效的,而且需要很长时间。有没有办法可以加快速度,或者我只能坐在这里等待厄运的纺车停止。

最佳答案

您可以直接使用 Dir 来检查,而不是循环遍历文件列表。如果文件存在,则为通配符。
例如。您可以使用 Dir("C:\Temp\myNumber*.pdf")查找名为 myNumberAndUnusefulText.pdf 的文件.所以如果你使用 fileName = Dir("Some\Directory\Here\" & CSheet & "*.pdf")它将返回以 CSheet 中的数字开头的文件的文件名.
首先将所有值进一步读入一个数组,然后处理该数组,这会使您的代码更快。对单元格的读取和写入操作会占用大量开销,因此速度很慢。通过将值读入一个数组,您可以将其减少为一个单元格读取和一个单元格写入操作。

Option Explicit

Public Sub LoopFilesImproved()
    Dim CCNums As Range
    Set CCNums = ThisWorkbook.Worksheets("Sheet1").Range("BC4:BC68512")  ' always specify in which sheet a range is!
    
    ' define output range
    Dim Output As Range
    Set Output = CCNums.Offset(ColumnOffset:=1)
    
    ' read output range into array for faster processing
    Dim OutputValues() As Variant
    OutputValues = Output.Value2
    
    ' read all values into an array for faster processing
    Dim CCNumsValues() As Variant
    CCNumsValues = CCNums.Value2
    
    ' loop through numbers and check if a file exists
    Dim iCCNum As Long
    For iCCNum = LBound(CCNumsValues, 1) To UBound(CCNumsValues, 1)
        Dim CSheet As String
        CSheet = Left$(CCNumsValues(iCCNum, 1), 6)
        
        Dim fileName As String
        fileName = Dir("Some\Directory\Here\" & CSheet & "*.pdf")
        
        If fileName <> vbNullString Then
            OutputValues(iCCNum, 1) = "Available"
        Else
            OutputValues(iCCNum, 1) = "Not Found"
        End If
    Next iCCNum
    
    ' write array values back to cell
    Output.Value2 = OutputValues
End Sub

关于excel - 高效使用 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72724929/

相关文章:

vba - 使用VBA在excel中导入网页数据

vba - 循环遍历一行并将单元格合并为标题vba

vba - 适用于 BoM 的 SolidWorks EPDM GetVar 无法在 VBA 中工作

excel - 突出显示具有数值的单元格

javascript - 如何在 node.js 中设置 xlsx 文件的样式

excel - 类型不匹配错误,Nothing 且循环未终止

excel - 使用 Excel 数据创建 Outlook session 请求

excel - Excel的 'Dependency-Chain'是增加还是减少?

excel - 宏中的 Text-To-Columns 将 24 时间转换为 12 小时格式

excel - 在 VBA 中键入比索的货币符号