Search code examples
vbafor-loopincrementactivexobject

Incrementing VBA For loop through command button


Good day!

I am currently having a slight issue with a command button, which, I would like to be able to do the following: format a specific row to a certain row height, add thick borders to a certain number of cells in this same row and counting and adding the number of rows thus produced to the initial number in the file. Basically, the button should enable the user of the spread sheet to add a new row with specific formatting into which the user will input data and keep track of the number of rows added.

My current code stands as is:

Option Explicit

Private Sub NewLineRedButton_Click()

    Dim i As Long
    Dim y As Long

    For y = ThisWorkbook.Worksheets("Flags").Cells(16.3) To y + 1
        ThisWorkbook.Worksheets("Flags").Cells(16, 3) = y + 1
        For i = 20 To i + y Step 1
            ThisWorkbook.Worksheets("Flags").Rows(i).RowHeight = 45
            ThisWorkbook.Worksheets("Flags").Cells(i, 1).Borders.LineStyle = xlContinuous
            ThisWorkbook.Worksheets("Flags").Cells(i, 1).Borders.Weight = xlMedium
        Next
    Next

End Sub

At the moment the code executes only for two rows below and stops. I am not quite sure, why...?


Solution

  • Writing a for loop like this

    For y = ThisWorkbook.Worksheets("Flags").Cells(16.3) To y + 1
    

    is the same as writing it like this

    For y = ThisWorkbook.Worksheets("Flags").Cells(16.3) To 1
    

    I'm guessing the value in the cell is zero so it will execute the loop for 0 and 1 - i.e. the two times you are seeing.

    You need something like

    lEndRow = lStartRow + (lRowCount - 1)
    For y = lStartRow to  lEndRow