将计算应用于整个范围,而不是遍历每个像元的VBA

时间:2019-03-08 17:45:46

标签: excel vba vectorization

所以我必须遍历大约10000个包含字符串的单元格,并将它们缩短为255个字符。我的实际代码是这样的:

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

但是,这非常慢,所以我想知道是否有在整个范围内执行一次该操作而不是遍历范围内的每个单元格,或者是否有其他方法比执行此操作更有效我的方式。

3 个答案:

答案 0 :(得分:3)

尝试一下:

HISAT/hisat2-2.1.0/hisat2 --p 8 --min-intronlen 60 --max-intronlen 6000 --dta -x Hisat2_index/arabidopsis -U data/1547_2015/Accessions/Alst-1_6989/transcriptome/fastq/trim/SRR3460433.fastq.bz2_trimmed.fq.gz,data/1547_2015/Accessions/Alst-1_6989/transcriptome/fastq/trim/SRR3460434.fastq.bz2_trimmed.fq.gz,data/1547_2015/Accessions/Alst-1_6989/transcriptome/fastq/trim/SRR3460435.fastq.bz2_trimmed.fq.gz,data/1547_2015/Accessions/Alst-1_6989/transcriptome/fastq/trim/SRR3460436.fastq.bz2_trimmed.fq.gz -S data/1547_2015/Accessions/Alst-1_6989/transcriptome/fastq/trim/Alst-1_6989.bam

处理成千上万的行或单元格时,数组是最好的选择。

答案 1 :(得分:1)

您尝试:

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

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

答案 2 :(得分:1)

或者这个:

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