Home » excel » excel – Speeding up calculations on a table

excel – Speeding up calculations on a table

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’ve got a table that will have different formulas for odd and even columns. I’m trying to loop through the table to do these calculations, but the problem is that it’s taking forever, even when my code doesn’t perform a calculation. Does anyone have suggestions on how I could improve my code? Here’s what I’ve got so far:

Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long
Dim i As Long
Dim i2 As Long
Dim even As Boolean

Set tbl = ActiveSheet.ListObjects("Table1")

With tbl.DataBodyRange
    tRows = .Rows.Count
    tCols = .Columns.Count
End With

'Start performing calculations
For i = 2 To tCols

    If i Mod 2 = 0 Then
        even = True
    Else
        even = False
    End If

    For i2 = 2 To tRows + 1
        If even Then
            'Formula for even columns
            Cells(i2, i) = "Even"
        Else
            'Formula for odd columns
            Cells(i2, i) = "Odd"
        End If
    Next i2

Next i
How to&Answers:

Imagine the following data:

enter image description here

Then run the following code:

Sub Test()

Dim tbl As ListObject: Set tbl = Sheet1.ListObjects("Table1")
tbl.DataBodyRange.FormulaR1C1 = "=IF(ISODD(COLUMN()),TRUE,FALSE)"

End Sub

With the following result:

enter image description here

Note that:

  • You must replace the TRUE part of my formula with your ODD formula.
  • You must replace the FALSE part of my formula with your EVEN formula.
  • I have used a explicit cell reference to Sheet1 using it’s CodeName. So change that accordingly

Regardless of amount of columns or rows, the whole .DataBodyRange has been filled according to the formula.