VBA代码用数字填充一个序列,从一个计算范围内活动行数的序列开始

时间:2017-02-11 14:20:15

标签: vba loops

我希望按顺序依赖于活动行数来填充序列。做这个的最好方式是什么?我的公式是在行中添加一个太多的数字。我希望它从1到70,但它也增加了71.

enter image description here

Sub copy_sequenc_down()


    Dim maxRowIndex As Integer

    maxRowIndex = ActiveSheet.Range("A1").CurrentRegion.Rows.count

    'set up starting point of repetition structure
    Range("a2").Select
    Dim rowCounter As Integer
    rowCounter = 1

    'begin populating sequence
    For rowCounter = 1 To maxRowIndex
        'populate number in sequence
        ActiveCell = rowCounter
        'go to next row
        ActiveCell.Offset(1).Select
    Next
End Sub

3 个答案:

答案 0 :(得分:0)

int main(){
    int closest;
    int temp;
    int a0 = 10, a1 = 20, a2 = 30; //and more..
    int user_input = 28;

    closest = abs(user_input - a0);
    temp = abs(user_input - a1);
    if (temp <= closest)
        closest = temp;
    //and so on
    return 0;

答案 1 :(得分:0)

您可以通过循环范围缩短代码

Sub copy_sequenc_down()
    Dim cell As Range

    For Each cell in Range("A2", Cells(Rows.Count, 1).End(xlUp))
        rowCounter = rowCounter + 1
        cell.Value = rowCounter
    Next
End Sub

答案 2 :(得分:0)

更快地将它们全部设置为:

Set rng = Range("A2").Resize(Range("B2").CurrentRegion.Rows.Count - 1)
rng.Formula = "=ROW()-1"
rng.Value2 = rng.Value2     ' optional to change the formulas to values

或更高级:

rng.Value2 = Evaluate("ROW(1:" & rng.Rows.Count & ")")

如果您将范围格式化为表格,则structured references会更容易一些:

[Table1[Column1]] = [Row(Table1[Column1])-1]

[Table1[Column1]] = [Row(Table1[Column1])-Row(Table1[#Headers])]