如何检查范围VBA中的单元格值

时间:2017-06-19 15:32:24

标签: excel vba excel-vba excel-2010

我正在尝试获取一系列单元格(B列是特定的)并找到该范围内值小于零的单元格并清除这些单元格的内容。有没有办法在不循环每个单元格的情况下执行此操作?该列是一个非常大的数据集,每周都会变长,因此循环会占用大量时间。

以下是我正在使用的当前循环

Dim sht As Worksheet
Dim LastColumn As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
lastrow = sht.Cells.Find("*", SearchOrder:=xlByRows, 
searchdirection:=xlPrevious).Row
for i=1 to lastrow
if sheets("time").cells(i, "B") then
sheets("time").cells(i, "B").clear
end if
next i

我试图检查然后可能删除的单元格包含公式

编辑:标记为已接受的答案加快了流程,但仍需要循环。如果有人有任何比发布更快的东西,请随意添加。

3 个答案:

答案 0 :(得分:2)

根据我的评论。我在50k行上运行它,花了很少的时间。

Option Explicit

Sub update_column()
Dim Column_to_run_on As String
Dim LR As Long, i As Long
Dim arr As Variant

'change as needed
Column_to_run_on = "D"

'change sheet as needed
With Sheets("Sheet1")
    LR = .Range(Column_to_run_on & "1048575").End(xlUp).Row

    '"2:" here as I assume you have a header row so need to start from row 2
    arr = .Range(Column_to_run_on & "2:" & Column_to_run_on & LR)

    For i = 1 To UBound(arr, 1)
        If arr(i, 1) < 0 Then
            arr(i, 1) = 0
        End If
    Next

    .Range(Column_to_run_on & "2:" & Column_to_run_on & LR).Value = arr
End With
End Sub

答案 1 :(得分:0)

不需要循环。假设我们有 B1 B21 的数据,如:

enter image description here

这个微小的宏:

Sub RemoveNegs()

    With Range("B1:B21")
        .Value = Evaluate("IF(" & .Address & " < 0,""""," & .Address & ")")
    End With


End Sub

将产生:

enter image description here

如果单元格包含公式,则不合适。

答案 2 :(得分:0)

我用vba数组对两种解决方案测试了lopps,在每种情况下循环速度至少快2到5倍:

Option Explicit

Sub fill()
Dim t As Double
t = Timer
Dim x&
Dim y&
Dim arr()
With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual

    ReDim arr(1 To 2000, 1 To 1000)

    For x = 1 To 1000
        For y = 1 To 2000
            arr(y, x) = Rnd() * 1111 - 555
        Next y
    Next x

    Range(Cells(1, 1), Cells(2000, 1000)).Value2 = arr

    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    Debug.Print Timer - t
End With
Erase arr

End Sub


Sub nega()
Dim t As Double
t = Timer
Dim x&
Dim y&
Dim arr()
With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual

    'With Range("A1", Cells(2000, 1000))
    '    .Value2 = Evaluate("if(" & .Address & " <0,""""," & .Address & ")")
    'End With


    'Range(Cells(1, 1), Cells(2000, 1000)).Replace "-*", ""

    arr = Range(Cells(1, 1), Cells(2000, 1000)).Value2

    For x = 1 To 1000
        For y = 1 To 2000
            If arr(y, x) < 0 Then arr(y, x) = vbNullString
        Next y
    Next x

    Range(Cells(1, 1), Cells(2000, 1000)).Value2 = arr

    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True

End With
Erase arr
Debug.Print Timer - t 
End Sub