【问题标题】:if-statement in a for-loop with a counter带有计数器的 for 循环中的 if 语句
【发布时间】:2014-08-03 13:14:47
【问题描述】:

我有以下情况我想不通。有没有办法在不覆盖自身的情况下在 if 循环中获取计数器。

我有这个代码:

lastrow = Sheets("sheetx").Cells.SpecialCells(xlCellTypeLastCell).Row

For a = 1 To lastrow
    If Sheets("sheetx").Cells(a, 1).Value = "aa" Then
        Sheets("sheetx").Cells(a, 2).Value = "zz"
    End If
    If Sheets("sheetx").Cells(a, 1).Value = "bb" Then
        Sheets("sheetx").Cells(a, 2).Value = "yy"
    End If
    If Sheets("sheetx").Cells(a, 1).Value = "cc" Then
        Sheets("sheetx").Cells(a, 2).Value = "zz"
    End If
    If Sheets("sheetx").Cells(a, 1).Value = "dd" Then
        Sheets("sheetx").Cells(a, 2).Value = "ww"
    End If
Next a

左边的数据就是我得到的。但我想把数据放在右边。当“aa”的 if 语句分配超过 8 次“zz”时,它必须停止(见右图)分配“zz”。有没有简单的方法来解决这个问题?

【问题讨论】:

    标签: excel if-statement for-loop excel-2013 vba


    【解决方案1】:

    您可以保留一个单独的计数器来计算"aa" 被替换的次数。像这样的:

    Dim aaCounter As Integer
    
    lastrow = Sheets("sheetx").Cells.SpecialCells(xlCellTypeLastCell).Row
    
    aaCounter = 1
    For a = 1 To lastrow
        If Sheets("sheetx").Cells(a, 1).Value = "aa" Then
            If aaCounter <= 8 Then
              Sheets("sheetx").Cells(a, 2).Value = "zz"
              aaCounter = aaCounter + 1
            End If
        End If
        If Sheets("sheetx").Cells(a, 1).Value = "bb" Then
            Sheets("sheetx").Cells(a, 2).Value = "yy"
        End If
        If Sheets("sheetx").Cells(a, 1).Value = "cc" Then
            Sheets("sheetx").Cells(a, 2).Value = "zz"
        End If
        If Sheets("sheetx").Cells(a, 1).Value = "dd" Then
            Sheets("sheetx").Cells(a, 2).Value = "ww"
        End If
    Next a
    

    如果您愿意,您可以对其他值执行类似操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多