简体   繁体   中英

VBA code takes long to run in Excel

Would appreciate it if someone can provide me with some help.

I have the following VBA code below that does the following

  • looks through the specified range in an Excel worksheet
  • when it finds a cell that matches today's date, it selects that cell

The problem is, this piece of code is looking through 1500 rows to find the cell with today's date, which takes some time. Any thoughts on how I can speed this up? Here's my code:

Dim DateRng As Range, DateCell As Range
Set DateRng = Range("1:1500")
For Each DateCell In DateRng
If DateCell.Value = Date Then DateCell.Select
Next

Thanks in advance!

Cheers

Your code is looping through 16384 columns by 1500 rows or 24,576,000 cells.

This code limits the search area to a much smaller range and also uses the Range.Find method. I think you will find it much faster.

Sub FindDate()
Dim DateRng As Range, DateCell As Range

Set DateRng = Range("A1:A1500")
With DateRng
    Set DateCell = .Find(Date)
    If Not DateCell Is Nothing Then
        DateCell.Select
    End If
End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM