简体   繁体   中英

Excel VBA how to set number sequence to start at middle of the row?

I previously have a Excel sheet with VBA coding that fills column, row 1 to 10 with the number 1, row 11 to 20 with number 2 and so on. The code I've used is as follows:

Sub fill()

  Dim ID
  ID = 1
  For c = 1 To 34

    ActiveWorkbook.Sheets("Sheet1").Cells(c, 1) = ID
    ActiveWorkbook.Sheets("Sheet1").Cells(c + 1, 1) = ID
    c = c + 1
    If (c Mod 10) = 0 Then
        ID = ID + 1
    End If

  Next c
End Sub

Now I want to change it so that the code starts at row 3 onwards. Meaning row 3 to 12 = 1, row 13 to 22 = 2 and so on. So I changed the 'For' statement to:

For c = 3 To 34

But what happens is that the number 1 appears from row 3 to row 10, and then continues with number 2 in row 11 to 20. Not what I was expecting.

在此处输入图片说明

Therefore, what would be the best method of changing the code?

If you want exactly the same output but two rows lower, you can use:

Sub fill()

  Dim ID
  ID = 1
  For c = 1 To 34

    ActiveWorkbook.Sheets("Sheet1").Cells(c + 2, 1) = ID
    ActiveWorkbook.Sheets("Sheet1").Cells(c + 3, 1) = ID
    c = c + 1
    If (c Mod 10) = 0 Then
        ID = ID + 1
    End If

  Next c
End Sub

If you still only want to go to row 34 but start in row 3, change the 34 to 32 in the above code.

You can also do it without looping and this is easier to adjust the parameters:

Sub fill()

    Const NUMBER_OF_ROWS As Long = 34
    Const START_ROW              As Long = 3
    Const ID                    As Long = 1
    Const NUMBER_IN_GROUP As Long = 10

    With ActiveWorkbook.Sheets("Sheet1").Cells(START_ROW, 1).Resize(NUMBER_OF_ROWS)
        .Value = .Parent.Evaluate("INDEX(INT((ROW(" & .Address & ")-" & START_ROW & ")/" & _
                            NUMBER_IN_GROUP & ")+" & ID & ",)")
    End With
End Sub

When i understand you write, this should work: You can use the loop how you did at the beginning. and just add plus 2 to c in the ActiveWorkbook.Sheets("Tabelle1").Cells(c + 2, 1) = ID

 Sub fill()

  Dim ID
  ID = 1
  For c = 1 To 34

    ActiveWorkbook.Sheets("Tabelle1").Cells(c + 2, 1) = ID
ActiveWorkbook.Sheets("Tabelle1").Cells(c + 3, 1) = ID
c= c+1
        If (c Mod 10) = 0 Then
            ID = ID + 1
        End If

  Next c
End Sub

something like that should be the simplest way:

Sub fill()
Dim i As Integer
Dim j As Integer

For i = 1 To 4
    For j = 1 To 10
        ActiveWorkbook.Sheets("Sheet1").Cells(j + (i - 1) * 10 + 2, 1) = i
    Next j
Next i
End Sub

EDIT: No, the simplest way would be type formula into A3:

=ROUNDDOWN(((ROW()-3))/10,0)+1

end drag it donw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM