带有运行总和的条件循环正在跳过值

时间:2016-04-26 15:36:41

标签: excel vba excel-vba loops

我创建此代码的目的是:

First Loop:

  • 遍历column O中的单元格以查找以DAAP开头的所有内容。
  • 如果DAAP左侧的单元格5列为空,则将右侧的单元格1列(这是一个数字)添加到Total。然后将单元格重命名为GAAF
  • 如果剩下的Cell 5列不为空,则只需将单元格重命名为GAAF

第二圈:

  • 查找GAAF中的所有column O个单元格,然后将单元格1列更改为Total

这是我的代码,它运行时没有错误,但什么也没做。我假设某些语法错误,所以它在错误的地方寻找,但我无法找到它!非常感谢任何帮助:)

Dim rng As Range
Dim lstRow As Long
Dim AUMCell As Range
Dim Total As Long

lstRow = Cells(Rows.Count, "O").End(xlUp).Row

Set rng = Range("O2", Cells(lstRow, "O"))

Total = 0

For Each AUMCell In rng
    If AUMCell.value = "DAAP" & "*" And AUMCell.Offset(0, -5).value = "" Then
        Total = Total + AUMCell.Offset(0, 1).Value
        AUMCell.value = "GAAF"
    ElseIf AUMCell.value = "DAAP" & "*" And AUMCell.Offset(0, -5).value <> "" Then
        AUMCell.value = "GAAF"
    End If
Next AUMCell

For Each AUMCell In rng
    If AUMCell.Value = "GAAF" Then
        AUMCell.Offset(0, 1).Value = Total
    End If
Next AUMCell

2 个答案:

答案 0 :(得分:0)

尝试替换此代码

For Each AUMCell In rng
    If AUMCell.value = "DAAP" & "*" And AUMCell.Offset(0, -5).value = "" Then
        Total = Total + AUMCell.Offset(0, 1).Value
        AUMCell.value = "GAAF"
    ElseIf AUMCell.value = "DAAP" & "*" And AUMCell.Offset(0, -5).value <> "" Then
        AUMCell.value = "GAAF"
    End If 
Next AUMCell

通过此代码

For Each AUMCell In rng
    If AUMCell.value like "DAAP*" Then 
        If AUMCell.Offset(0, -5).value = "" Then
            Total = Total + AUMCell.Offset(0, 1).Value
        End If        
        AUMCell.value = "GAAF"
    End If
Next AUMCell

P.S。:对不起我的英文

答案 1 :(得分:0)

虽然代码较长,但Find的执行速度比循环每个单元格要快得多。

    Sub Recut()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range

    Dim aCell As Range
    Dim bCell As Range
    Dim ws As Worksheet
    Dim SearchString As String


    Set ws = ActiveSheet
    Set rng1 = ws.Range("O:O")

    SearchString = "DAAP"

    Set aCell = rng1.Find(SearchString, , xlFormulas, xlPart, xlByRows, xlNext)

    If Not aCell Is Nothing Then
        Set bCell = aCell
        If Left$(aCell.Value, 4) = SearchString Then Set rng2 = aCell
        Do
            Set aCell = rng1.FindNext(After:=aCell)
             If Not aCell Is Nothing Then
                If aCell.Address = bCell.Address Then Exit Do
                 If Left$(aCell.Value, 4) = SearchString Then
                    If Not rng2 Is Nothing Then
                        Set rng2 = Union(rng2, aCell)
                    Else
                        Set rng2 = aCell
                    End If
                 End If
            Else
                Exit Do
            End If
        Loop
    Else
        MsgBox SearchString & " not Found"
        Exit Sub
    End If

    If rng2 Is Nothing Then Exit Sub

    For Each rng3 In rng2
      If Len(rng3.Offset(0, -5)) = 0 Then Total = Total + rng3.Offset(0, 1).Value
      rng3.Value = "GAFF"
    Next

    MsgBox Total

End Sub