简体   繁体   中英

Apply calculations to whole range instead of looping though each cell VBA

So I have to loop through a range of about 10000 cells containing strings and shortening them to 255 characters. My actual code is like this:

For i = firstRow to lastRow
    Range("X" & i) = Left(Range("X" & i),255)
Next i

However, this is extremely slow, so I was wondering if there was anyway to do that once on the whole range instead of looping through each cell of the range, or if there was any other way that is more efficient than doing it my way.

Try this:

Sub short()

    Dim arr, FirstRow As Long, LastRow As Long, i As Long

    arr = ThisWorkbook.Sheets("yoursheetname").Range("X" & FirstRow, "X" & LastRow).Value

    For i = 1 To UBound(arr)
        arr(i, 1) = Left(arr(i, 1), 255)
    Next i

    ThisWorkbook.Sheets("yoursheetname").Range("X" & FirstRow, "X" & LastRow).Value = arr



End Sub

When you work with thousands of rows or cells, arrays are the best way to go.

You try:

Option Explicit

Sub test()

    Dim Lastrow As Long, FirstRow, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "X").End(xlUp).Row
        FirstRow = 1

        For i = FirstRow To Lastrow
            .Range("X" & i).Value = Left(.Range("X" & i).Value, 255)
        Next i

    End With

End Sub

Or

Option Explicit

Sub test()

    Dim Lastrow As Long, FirstRow
    Dim rng As Range, cell As Range

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "X").End(xlUp).Row
        FirstRow = 1
        Set rng = .Range(.Cells(FirstRow, 24), Cells(Lastrow, 24))

        For Each cell In rng
            cell.Value = Left(cell.Value, 255)
        Next cell

    End With

End Sub

Or this:

With ActiveSheet.Range("X" & firstRow & ":X" & lastRow)
    .Value = .Parent.Evaluate("LEFT(" & rng.Address & ",255)")
End With

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