VBA:我想按顺序对某个范围内的单元格进行编号,直至达到最大值

问题描述 投票:0回答:1

所以我想对以下范围内的单元格进行编号:

R1 = Union(Range("A2:A24"), Range("E2:E24"), Range("I2:I17")).Select

我的目标是为它们分配数字,从 1 开始一直到设定的最大值。

Var = Application.WorksheetFunction.CountIf(Range("C6:C" & L1), "2")

如果 Var 小于范围内的单元格数量,我希望剩余的单元格为空。

excel vba
1个回答
0
投票

您可以使用以下模板

    Sub NumberCellsInRange()
        Dim rng As Range
        Dim cell As Range
        Dim maxNumber As Long
        Dim currentNumber As Long
        Dim totalCells As Long
    
        ' Define the range you want to work with
        Set rng = Range("A1:b5") ' Change this to your desired range
        ' In your case, you don't need to select it
        ' R1 = Union(Range("A2:A24"), Range("E2:E24"), Range("I2:I17"))
        
        ' How many cells to number
        maxNumber = 5
        ' In your case, why var? It's a number
        ' Var = Application.WorksheetFunction.CountIf(Range("C6:C" & L1), "2")
        
        ' Initialize the counter
        currentNumber = 1
        totalCells = rng.Count
    
        ' Loop through each cell in the range
        For Each cell In rng
            If currentNumber <= maxNumber Then
                cell.Value = currentNumber
                currentNumber = currentNumber + 1
            Else
                cell.Value = "" ' Leave remaining cells empty
            End If
        Next cell
    End Sub
© www.soinside.com 2019 - 2024. All rights reserved.