VBA:根据相邻单元格编辑单元格值,无需循环

时间:2018-05-04 22:08:26

标签: excel vba excel-vba performance

目前,我有一个代码,如果同一行的不同列中的单元格不为空,则将x放在单元格中。像这样:

for i = 2 to lLastRow
    if Cells(i,1) <> "" then cells(i,2) = "x"
next i

但我有一个案例,我的数据集是成千上万的行,而这个循环正在吸引时间。有没有办法在没有循环的情况下做到这一点?

3 个答案:

答案 0 :(得分:1)

使用AutoFilter

Option Explicit

Public Sub ReplaceBlankOffset()
    Dim col1 As Range, col2 As Range
    Set col1 = ActiveSheet.UsedRange.Columns("E")
    Set col2 = ActiveSheet.UsedRange.Columns("F")

    col1.AutoFilter Field:=1, Criteria1:="<>"
    If col1.SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
        col2.Offset(1).Resize(col2.Cells.Count - 1).FormulaR1C1 = "x"
    End If
    col1.AutoFilter
End Sub
Rows: 500,001 - Time: 1.078 sec

答案 1 :(得分:1)

阵列方法最有可能提供最快的解决方案:

Option Explicit

Sub main()
    Dim i As Long
    Dim vals As Variant

    With Range("A2", Cells(Rows.Count, 1).End(xlUp))
        vals = .Value
        For i = 1 To UBound(vals)
            If Not IsEmpty(vals(i, 1)) Then vals(i, 1) = "x"
        Next
        .Offset(, 1).Value = vals
    End With
End Sub

虽然无循环解决方案可能是:

Range("A2", Cells(lLastRow,1)).SpecialCells(xlCellTypeConstants).Offset(,1) = "x"

虽然最有可能很慢

答案 2 :(得分:0)

给它一个镜头..............它不需要循环:

Sub Killer_V2()
    Dim rng2 As Range, rng As Range
    Dim N As Long, s As String
    Dim critCol As String, helpCol As String

    critCol = "A"
    helpCol = "B"
    N = Cells(Rows.Count, critCol).End(xlUp).Row
    Set rng = Range(Cells(1, critCol), Cells(N, critCol))
    s = "=IF(" & rng.Address & "<>"""",""x"","""")"

    Set rng2 = Range(Cells(1, helpCol), Cells(N, helpCol))
    rng2.Value = Evaluate(s)
End Sub