Search code examples
excelvbauserform

Is there a way to loop a command button in a userform based off of a number input from a textbox?


As with my other post, please forgive my lack of knowledge in this subject, I am very new to coding.

I have a userform that has multiple textboxes where a user can input data. Once that data is input into the form, the user clicks a command button and the code outputs the data to the first empty row it finds. This part of the code works very well.

My question: How can I loop the command button to click itself "n" times where n = data_points_textbox.Value. My goal is to be able to get the macro to generate large amounts of data with a single click.

I've tried posts like this one VBA loop through buttons on UserForm

and

https://social.msdn.microsoft.com/Forums/en-US/bcb8b8b4-4bcf-404d-9fdb-a9d5f31f6b19/loop-through-excel-userform-textcombo-box-and-write-to-worksheet?forum=isvvba

While helpful, I am not sure these posts quite apply to my situation and I'm not sure I honestly understand what they are doing.

'Here is an excerpt of the code I am using, for various reasons I can't post all of it

Private Sub Data_Generator_Initialize()

'Empty Type_textbox
type_textbox.value = ""

End Sub 

Private Sub Generate_data_button_Click()

'Make sheet1 active
Sheet1.activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer data to sheet1
Cells(emptyRow, 1).Value = type_textbox.Value 

End Sub 

'I have about 20 additional cells that are populated with data from various textboxes but I think this illustrates the point


Solution

  • The way I understand the problem:

    1. A button on a UF currently outputs values from textboxes to a single row
    2. You want the output to an x amount of rows, based on the value of another textbox

    This could be achieved by looping the code inside the macro linked to the command button

    Private Sub Generate_data_button_Click()
    Dim arr(5) As String
    Dim i As Long
    Dim LRow As Long
    Dim FEmptyRow As Long
    
    'Using 6 textboxes as an example. Change to your configuration 
    arr(0) = TextBox1.Value
    arr(1) = TextBox2.Value
    arr(2) = TextBox3.Value
    arr(3) = TextBox4.Value
    arr(4) = TextBox5.Value
    arr(5) = TextBox6.Value
    
    With Workbooks(REF).Sheets(REF)
        For i = 1 To data_points_textbox.Value
            LRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 'determines the last filled row in column A
            FEmptyRow = .Cells(1, "A").End(xlDown).Row + 1 'determines the first empty row as seen from the top row (using this can cause filled rows below it to be overwritten!)
    
            .Range("A" & LRow & ":F" & LRow).Value = arr
            '.Range("A" & FEmptyRow & ":F" & FEmptyRow).Value = arr  'Alternative with the first empty row
        Next i
    End With
    End Sub