excel - 自动填充动态数据范围内的增量数

标签 excel vba

我被困在我的 vba 代码中,似乎我设置了一个错误的循环。非常感谢您的一些建议!非常感谢!!

Sub code()

Dim lastRow As Long
Dim k As Integer
Dim rowPtr As Long

lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For rowPtr = 2 To lastRow
     
If Range("A" & rowPtr + 1) <> Range("A" & rowPtr) Then
k = 1
Range("B" & rowPtr) = k

Else
        
If Range("A" & rowPtr + 1) = Range("A" & rowPtr) Then
Range("B" & rowPtr) = k
             
End If
k = k + 1
End If

Next
End Sub

上面是我的代码,现在我的 VBA 结果如下: screenshot

C 列是我理想的代码结果

最佳答案

排名代表(重复值)

  • 调整常量部分中的值。
  • 请注意,Range("A"& rowPtr)Cells(rowPtr, "A")Cells(rowPtr, 1)Range("A"& Rows.Count)Cells(Rows.Count, "A")Cells(Rows .计数,1)
Option Explicit

Sub rankReps()

    Const FirstRow As Long = 2
    Const sCol As String = "A"
    Const dCol As String = "B"
    
    Dim cOffset As Long: cOffset = Columns(dCol).Column - Columns(sCol).Column
    
    Dim LastRow As Long: LastRow = Range(sCol & Rows.Count).End(xlUp).Row
    If LastRow < FirstRow Then
         MsgBox "No data", vbCritical, "No Data"
         Exit Sub
    End If
    
    ' Write first.
    Range(sCol & FirstRow).Offset(, cOffset).Value = 1
    
    ' Write remainder.
    If LastRow > FirstRow Then
        Dim cCell As Range ' Current Cell
        Dim r As Long ' Row Counter
        Dim rk As Long: rk = 1 ' Rank Counter
        For r = FirstRow + 1 To LastRow ' +1: the first is already written
            Set cCell = Range(sCol & r)
            If cCell.Value = cCell.Offset(-1).Value Then
                rk = rk + 1
            Else
                rk = 1
            End If
            cCell.Offset(, cOffset).Value = rk
        Next r
    End If
    
End Sub

关于excel - 自动填充动态数据范围内的增量数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67366062/

相关文章:

java - Apache Poi - 如何读取 xlsx 并在不包含信息的行上写入?

Excel VBA : Secure way to get user's database login/password for connection string?

excel - 使用 Excel 仅将唯一列转置为标题行

vba - 在 Excel VBA 中从 "this sheet"选择到末尾

excel - VBA 的 Sumif 始终使用前一列的前一个单元格作为参数,直到列结束

excel - 在 Excel 中从 URL 加载图像

excel - 高级筛选器无法识别公式返回的空白

excel - 将不同工作簿中的工作表复制到此工作簿引用问题

excel - 如何更换一个?通过 é 在 Excel 工作表中

vba - 找不到 Excel VBA 文件