Excel VBA: Writing an array to cells is very slow

后端 未结 2 1114
长情又很酷
长情又很酷 2020-12-22 03:52

I am working with VBA in Excel to retrieve some information from the Reuters 3000 Database. The data I retrieve comes as a bidimensional array consisting of one column hold

相关标签:
2条回答
  • 2020-12-22 04:14

    By not selecting the sheet, you can add a bit more speed. Instead of

    Sheets("Data").Activate
    Date_Arr = Range(Cells(3, 106), Cells(3, 106).End(xlDown))
    loadDateArray = Date_Arr
    

    Try

    With Sheets("Data")
    Date_Arr = .Range(Cells(3, 106), Cells(3, 106).End(xlDown))
    End With
    
    0 讨论(0)
  • 2020-12-22 04:18

    This is what I did to improve the performance:

    • Avoid selecting the cell when the value is going to be written. This was a suggestion of Tim Williams.
    • I set the property Application.Calculation to xlCalculationManual
    • Instead of using the Find() function to search for the date, I loaded all the dates from the worksheet into an array and iterate over this array to get the row number. This turns out to be faster than the Find() function.

      Private Function loadDateArray() As Variant
      
          Dim Date_Arr() As Variant
      
          Sheets("Data").Activate
          Date_Arr = Range(Cells(3, 106), Cells(3, 106).End(xlDown))
          loadDateArray = Date_Arr
      
      End Function
      
      Private Function getDateRow(dateArray As Variant, dateToLook As Variant)
      
          Dim i As Double: Dim dateRow As Double
      
          For i = LBound(dateArray, 1) To UBound(dateArray, 1)
              If dateArray(i, 1) = dateToLook Then
                  dateRow = i
                  Exit For
              End If
          Next i
      
          getDateRow = dateRow
      
      End Function
      

    Thank you all for your help!

    0 讨论(0)
提交回复
热议问题